【问题标题】:Canvas HTML5 - Change the background color after image drawingCanvas HTML5 - 绘制图像后更改背景颜色
【发布时间】:2020-08-04 19:22:57
【问题描述】:

我在绘制图像后搜索更改图像的背景颜色。

我有一个颜色选择器,用户可以在其中更改图像背景的颜色。

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

我想在图像渲染后更改字体颜色,因为图像渲染太长,用户应该能够更改图像颜色。

【问题讨论】:

    标签: html canvas html5-canvas


    【解决方案1】:

    通过 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;
    }
    

    您也可以使用OffscreenCanvasImageBitmap,尽管复制的方法与上面略有不同。 (同时检查浏览器支持)

    渲染层

    获得前景像素的副本后,您可以渲染背景,然后渲染前景以获得最终结果

    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,就会复制画布

    【讨论】:

    • 是的!第三种方法有效!你救了我很多次,谢谢!
    猜你喜欢
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 2014-04-26
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多