Created
December 1, 2022 10:52
-
-
Save josephrocca/d82b607745dabfdd5bccf03bc0334052 to your computer and use it in GitHub Desktop.
RGBA data to canvas - create a canvas from RGB data
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
function createCanvasFromRGBAData(data, width, height) { | |
// `data` should look something like [[123,32,40,255], [3,233,42,120], ...] | |
if(width*height !== data.length) throw new Error("width*height should equal data.length"); | |
let canvas = document.createElement("canvas"); | |
canvas.width = width; | |
canvas.height = height; | |
let ctx = canvas.getContext("2d"); | |
let imgData = ctx.createImageData(width, height); | |
for(let i = 0; i < data.length; i++) { | |
imgData.data[i*4+0] = data[i][0]; | |
imgData.data[i*4+1] = data[i][1]; | |
imgData.data[i*4+2] = data[i][2]; | |
imgData.data[i*4+3] = data[i][3]; | |
} | |
ctx.putImageData(imgData, 0, 0); | |
return canvas; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment