简体   繁体   English

使用HTML5 canvas和getImageData的透明像素?

[英]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. 所以我将它们绘制到一个临时画布上,然后使用getImageData函数。 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? 我的image有一些透明像素但在此之后imageData中没有透明像素我该如何解决这个问题?

Is there any way to convert Html Image to ImageData, so I can process it and then draw to canvas? 有没有办法将Html Image转换为ImageData,所以我可以处理它然后绘制到画布?

your imageData should contain alpha channel. 你的imageData应该包含alpha通道。

However, putImageData will replace the pixel value in the context. 但是,putImageData将替换上下文中的像素值。 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). 所以,您应该看到的是画布背后的像素(在大多数情况下,是html页面的body标签的像素颜色)。

What you have to do: 你要做什么:

  • use a temporaty canvas to get image data is the good way 使用临时画布获取图像数据是一种好方法
  • modifiy the imageData as you need 根据需要修改imageData
  • don't try to put this imageData back in the conetext with a putImageData, it won't behave as you wish 不要尝试将此imageData放回使用putImageData的conetext中,它将不会按您的意愿运行
  • but create a new Image object and give it the imageData as source (yes, it works :)) 但创建一个新的Image对象,并将imageData作为源(是的,它工作:))
  • use drawImage to draw back the image 使用drawImage绘制图像

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. 它应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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