简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM