I’m currently setting individual pixels on the canvas within a loop using the fillRect method like so:
context.fillStyle = "rgba("+colourR+","+colourG+","+colourB+",255)";
context.fillRect( x, y, 1, 1 )
This method works fine, however it, and putImageData, is very slow. So I’ve decided to try and set the pixels individually within the loop, then use a single call to putImageData when ready to output to the screen, like so:
var screenImageData = context.getImageData(0,0,800,600);
var pixelBuffer = screenImageData.data;
pixelBuffer[(x*4) + (y*(screenImageData.width * 4))] = colourR;
pixelBuffer[(x*4) + (y*(screenImageData.width * 4)) + 1] = colourG;
pixelBuffer[(x*4) + (y*(screenImageData.width * 4)) + 2] = colourB;
pixelBuffer[(x*4) + (y*(screenImageData.width * 4)) + 3] = 255;
...
context.putImageData(screenImageData,0,0);
However, this generates a completely different output to the fillRect method (it just looks like jumbled up garbage). What am I doing wrong here?
The problem here was in the way x and y were calculated, apparently the putImageData converts them to ints automatically. Using Math.floor on them was all that was required.