Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 canvas image caching/putImageData questions

I'm using the HTML5 canvas to load a single instance of an image which I then blit multiple times onto a single canvas. The image needs some slight pixel-based manipulation in order to customise it. My initial plan of attack had been to load the image, blit it to a backing canvas, draw my modifications on-top of it, and then grab the image data and cache it for future use.

Here's some code I've written to that effect:

context.drawImage(img, 0, 0);
context.fillStyle = '#ffffff';
context.fillRect(0, 0, 2, 2);  // Draw a 2x2 rectangle of white pixels on the top left of the image

imageData = context.getImageData(0, 0, img.width, img.height);
cusomImage = imageData;

While this works, I've noticed that my image (which is a transparent PNG) does not maintain transparency. Instead, when using putImageData to place it onto my front-facing canvas, it is rendered with a black background. How do I maintain transparency?

Any suggestions are welcome!

like image 716
ndg Avatar asked Mar 06 '11 13:03

ndg


1 Answers

putImageData() does not do what you might first expect: http://dropshado.ws/post/1244700472/putimagedata-is-a-complete-jerk

putImageData() direct overrides the pixels of the canvas. So if you draw over something else on the same canvas it will not draw "over" it, it will instead replace the pixels of the canvas in the area with it's pixels.

I ran into this exact issue and finally found out why.

As for a solution, I haven't tried this yet but it seems promising: Why is putImageData so slow?

[EDIT]: I tested this method and it works fine for me, my data is now displaying transparency correctly.

like image 78
Ryan Badour Avatar answered Sep 20 '22 10:09

Ryan Badour