这有点像线程死灵法,但我刚刚遇到了这个问题并有解决方案,如果不是针对原始海报,那么对于像我这样来自谷歌的人。
如前所述,putImageData 直接替换像素而不是 alpha 混合,但这也意味着它会保留您的 alpha 数据。然后,您可以使用 drawImage 使用 alpha 混合重绘该图像。
举个例子,假设我们有一个 200 x 100 像素的画布和一个 100 x 100 的 imageData 对象。
// our canvas
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
// our imageData, created in whatever fashion, with alpha as appropriate...
var data = /* ... */
// lets make the right half of our canvas blue
ctx.fillStyle="blue";
ctx.rect(100, 0, 100, 100);
ctx.fill();
// now draw our image data to the left (white) half, pixels are replaced
ctx.putImageData(data, 0, 0, 100, 100);
// now the magic, draw the canvas to itself with clipping
ctx.drawImage(canvas, 100, 0, 100, 100, 100, 0, 100, 100);
瞧。图像的右半部分现在是与蓝色背景混合的图像数据,在硬件辅助下渲染。