Skip to content
Advertisement

HTML canvas image from rgb values

I have three 12×12 arrays, each with R, G and B values. How would I go about outputting the image (12×12) using HTML Canvas? I’ve come across Canvas demos that show drawing lines and whatnot, but nothing like providing some RGB arrays to produce something.

Any guidance is greatly appreciated.

Advertisement

Answer

You can use the fillRect method, described here : http://www.w3schools.com/tags/canvas_fillrect.asp

Each rectangle would match one table cell. You’d have to decide how large each of those rectangles would be : one pixel high and wide, or much more. Say we call this value pixelSize.

You create your canvas, get the context, define maxRows and maxColumns (here both would be 12). Then you iterate with two nested loops :

for(row=0; row<maxRows; ++row) {
    for(column=0; row<maxColumns; ++column) {
        ctx.fillStyle = 'rgb(' + rTable[row][column] + ',' + gTable[row][column] + 
                           ',' + bTable[row][column] + ')';
        ctx.fillRect(column*pixelSize,
                 row*pixelSize,
                 pixelSize,
                 pixelSize);            
    }
}

Then draw the context…

(edited : changed rect into fillRect as per markE’s remark)

Advertisement