[英]Canvas HTML5 - Change the background color after image drawing
我搜索以在图像绘制后更改图像的背景颜色。
我有一个颜色选择器,用户可以在其中更改图像背景的颜色。
this.picker.onChange = async (color) => {
const colorPicked = color;
this.context.fillStyle = colorPicked;
this.context.fillRect(0, 0, 1000, 1000);
}
// ...
// The event call this function when it's ready
buildImageProcess(this.context);
// User can use the color picker to change the background color
我想在图像渲染后更改字体颜色,因为图像渲染时间太长,用户应该能够更改图像颜色。
如果背景是透明的,则更改 canvas CSS background-color
。
如果您希望将 canvas 像素设置为颜色,则使用ctx.globalCompositeOperation = "destination-over"
仅在透明和半透明像素上渲染。
如果背景像素已经有颜色,那就有问题了。
这是问题最少的方法。 实际上,它创建了第二层(前景),您可以在背景(层)上渲染
复制一个canvas(前台)
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
并且 canvas 将被复制
您可以轻松更改 canvas-div 的背景颜色,因此它实际上不会成为 canvas 绘图的一部分。 这样您就不需要复制/删除和创建现有图层。 如果您想将 eG 下载您的 canvas 为 png,只需将 bg 添加为矩形即可
// draws following behind existing
ctx.globalCompositeOperation = 'destination-over';
ctx.fillStyle = canvas.style.backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
工作示例: https://github.com/BarbWire-1/lineIt或https://line-it.netlify.app/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.