在 HTML5 Canvas 上,在 JavaScript 中,我使用屏幕外 Canvas 元素来绘制图像。然后我将该图像的一部分传输到屏幕上的另一个 Canvas 上。原始图像是带有 alpha channel 的 png。然而,当图像绘制到屏幕上时,它的 Alpha channel 就消失了,只有白色背景。
这是有道理的,但我找不到太多有关如何对图像进行采样、在屏幕外执行某些操作,然后将图像传输到屏幕 Canvas 且其 Alpha channel 完好无损的文档。
这是一个小演示(抱歉,它是从一段更大的代码中破解出来的):
//this is all nested in an MVC view, using jQuery/Backbone
this.pasteboard = $("<canvas/>").attr("width",1200).attr("height",600)
this.pasteboard = this.pasteboard[0].getContext("2d");
var img = $("<img/>");
var t = this;
img.load(function(){
t.pasteboard.save();
t.pasteboard.clearRect(0,0,args.width,args.height)
t.pasteboard.drawImage(this,0,0);
log("obj args:",args)
o.imageData = t.pasteboard.getImageData(0,0,args.width,args.height);
t.pasteboard.restore();
o.ready = true;
o.trigger("ready",args);
}).attr("src",args.src);
// and somewhere else in the view object i use
this.ctx.putImageData(myimagedataobjecthere,0,0);
// all works fine except the alpha is now white background..
这大概是因为 getimagedata 和 putimagedata 之间缺乏 Alpha channel 的保留?
有人对此有任何指示吗?就像我提到的,我没有找到任何关于此的直接文档...
非常感谢
一个
最佳答案
The original image is a png with an alpha channel. however by the time that the image is drawn onto the screen it's alpha channel is gone and it just has a white background.
等等,情况根本不应该是这样的。如果情况确实如此,我认为您的代码中的其他地方有问题。
下面是一个示例,将透明图像绘制到一个 Canvas 上,并在其之前和之后绘制内容,然后将该 Canvas 绘制到第二个 Canvas 上,保持透明度不变:
无论如何,getImageData 和 PutImageData 绝对会保留 Alpha channel ,您在这里执行的其他操作一定是问题所在。
关于javascript - 获取带有原始图像 alpha 的图像数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9547346/