[英]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.