I'm just learning how to use the HTML5 canvas element. I've been successful in drawing rectangles, calling getImageData
, manipulating pixels and then putImageData
to see the rectangles change colour, etc.
Now I'm trying to load an image into the canvas I've hit a snag. After calling drawImage
on the canvas's context, fillRect
only draws in areas that don't have an image drawn into them, like it's drawing the rectangles behind the images, even though it's called after drawImage
. Also, putImageData
stops working, even on the visible areas containing rectangles, my pixel manipulation no longer happens. If I comment out the line with drawImage
, it works again.
What I want to be able to do is manipulate pixels in the image the same way I was doing with the rectangles. Is there any reason why this wouldn't work?
Draw Image code:
var img = new Image();
img.onload = function () {
//comment out the following line, everything works, but no image on canvas
//if it's left in, the image sits over the rectangles, and the pixel
//manipulation does not occur
context.drawImage(img, 0, 0, width / 2, height / 2);
}
img.src = path;
Draw Rectangles code:
for (var i = 0; i < amount; i++)
{
x = random(width - size);
y = random(height - size);
context.fillStyle = randomColor();
context.fillRect(x, y, size, size);
}
Maniuplate pixels code:
var imgd = context.getImageData(0, 0, width, height);
var pix = imgd.data;
//loop through and do stuff
context.putImageData(imgd, 0, 0);