通过 CSS
如果背景是透明的,则更改画布 CSS background-color。
通过全局复合操作
如果您希望画布像素设置为彩色,则使用ctx.globalCompositeOperation = "destination-over" 仅在透明和半透明像素上进行渲染。
如果背景像素已经有颜色,那就有问题了。
通过前景画布的副本
这是问题最少的方法。实际上,它创建了第二个图层(前景),您可以在背景(图层)上进行渲染
复制画布
复制画布(前景)
function copyCanvas(canvas) {
const copy = document.createElement("canvas");
copy.width = canvas.width;
copy.height = canvas.height;
const ctx = copy.getContext("2d");
ctx.drawImage(canvas, 0, 0); // render canvas to new canvas
return copy;
}
您也可以使用OffscreenCanvas 或ImageBitmap,尽管复制的方法与上面略有不同。 (同时检查浏览器支持)
渲染层
获得前景像素的副本后,您可以渲染背景,然后渲染前景以获得最终结果
this.picker.onChange = async (color) => {
const ctx = this.context;
if (this.foreGround === undefined) { // create copy only when needed
this.foreGround = copyCanvas(ctx.canvas);
}
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // in case color is semi transparent
ctx.fillStyle = color;
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(this.foreGround, 0, 0);
}
如果您更改前景像素,只需创建更改的新副本。例如,在上面的示例中,只需在添加背景之前设置this.foreGround = undefined,就会复制画布