I was playing around with pixel-level manipulations on an HTML canvas and ran into a bug with the putImageData()
function. Here's my code:
var can = document.getElementById("canvasID");
var ctx = can.getContext("2d");
var picToAlter = document.getElementById("image");
var pix = ctx.createImageData(1, 1);
var colData = pix.data;
colData[someNumber] = someValue;
ctx.drawImage("image", 0, 0);
for(let i=0;i<=can.width; i+10){
ctx.putImageData(pix, i, 0);
}
When I try to run this code in my browser (Firefox) the page simply fails to load no matter how long I wait, and, eventually, asks me if I want to stop the loading process. The problem seems to lie with my for-loop, because if I run a single instance of the code, it works. The moment I put it in a loop, though, it goes back to not loading. This is true even if I use a while-loop instead. I know that putImageData
can be slow, but I feel like I'm missing something obvious that makes the loop infinite, but I just can't find it.
If you are trying to grab image data immediately (without preloading), you probably see a blank canvas. You should only run your code after preloading the image.
picToAlter.addEventListener('load', yourDrawingMethod)
Also, your for-loop is probably not behaving how you would expect. You don't want to hit can.width
because it would actually be out of bounds because it's starting at zero. Also, your iteration statement isn't actually iterating. You need to use an assignment operator like i = i+10
or i+=10
. Taking those issues into consideration, you would end up with something like this...
for(let i = 0; i < can.width; i+=10){
// ...
}