Created
May 9, 2019 16:40
-
-
Save pseudosavant/115be60d73667ecc8810e37e580284ad to your computer and use it in GitHub Desktop.
Utility function for generating 1px x 1px PNGs data URI with a solid color. Useful for things like setting `<video>` `poster` to a color since CSS can't style that
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Usage example: document.querySelector('video').poster = createColorDataURI(50,100,150); | |
function createColorDataURI(r, g, b, a) { | |
const canvas = document.createElement('canvas'); | |
canvas.width = 1; | |
canvas.height = 1; | |
const context = canvas.getContext('2d'); | |
const imageData = context.getImageData(0, 0, 1, 1); | |
const subPixels = imageData.data; | |
subPixels[0] = r || 0; // r | |
subPixels[1] = g || 0; // g | |
subPixels[2] = b || 0; // b | |
subPixels[3] = a || 255; | |
context.putImageData(imageData, 0, 0); | |
return canvas.toDataURL('image/png'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment