Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transparent pixels using HTML5 canvas and getImageData?

In my application I need to get some images, process them, and save for later use. So I'm drawing them to a temporary canvas, then getting with getImageData function. But in output transparency is lost...

Here is my code:

var tempCanvas = document.createElement('canvas');
var tempContext = tempCanvas.getContext('2d');

tempContext.drawImage(image, 0, 0);
var imageData = tempContext.getImageData(0, 0, image.width, image.height);

My image has some transparent pixels but after this there are no transparent pixels in imageData how can I solve this issue?

Is there any way to convert Html Image to ImageData, so I can process it and then draw to canvas?

like image 550
shift66 Avatar asked Jul 23 '12 11:07

shift66


1 Answers

your imageData should contain alpha channel.

However, putImageData will replace the pixel value in the context. It won't merge it with the previous value of the pixel in the context, it will replace it. So, what you should see is the pixel behind the canvas (in most of cases, the pixel color of the body tag of your html page).

What you have to do:

  • use a temporaty canvas to get image data is the good way
  • modifiy the imageData as you need
  • don't try to put this imageData back in the conetext with a putImageData, it won't behave as you wish
  • but create a new Image object and give it the imageData as source (yes, it works :))
  • use drawImage to draw back the image

example of code:

var tempCanvas = document.createElement('canvas');
var tempContext = tempCanvas.getContext('2d');

tempContext.drawImage(image, 0, 0);
var imageData = tempContext.getImageData(0, 0, image.width, image.height);

//modify here the imageData as you need

var img = new Image();
img.src = imageData;
context.drawImage(img, 0, 0); //the true context of the canvas

It should works.

like image 136
Gwennael Buchet Avatar answered Oct 27 '22 17:10

Gwennael Buchet