intl
intl

Reputation: 2773

HTML canvas image from rgb values

I have three 12x12 arrays, each with R, G and B values. How would I go about outputting the image (12x12) 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.

Upvotes: 1

Views: 1869

Answers (2)

joe
joe

Reputation: 5522

The function below, if RGBA data of the form [[123,32,40,255], [3,233,42,120], ...], will return a canvas with that data:

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;
}

However, in your case, you have one 12x12 array for each of red, green and blue. In other words, your data is of "shape" [C,W,H], buSo you need to transform your data first. I'll do a 3x3 example instead of 12x12 so it's easier to type:

// an array of three 3x3 arrays:
let colorChannels = [
  [[0,0,0],[0,0,0],[0,0,0]], // red
  [[0,0,0],[0,0,0],[0,0,0]], // green
  [[0,0,0],[0,0,0],[0,0,0]], // blue
];

let RGBA = [];
for(let x = 0; x < 3; x++) {
  for(let y = 0; y < 3; y++) {
    RGBA.push(colorChannels[0][x][y]); // red
    RGBA.push(colorChannels[1][x][y]); // green
    RGBA.push(colorChannels[2][x][y]); // blue
    RGBA.push(255); // alpha (transparency)
  }
}

let canvas = createCanvasFromRGBAData(RGBA, 3, 3);

Upvotes: 0

Mathias Dolidon
Mathias Dolidon

Reputation: 3903

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)

Upvotes: 4

Related Questions