1

我发现这段代码可以为画布图像文件着色。我想知道在此着色上下文中使用什么 ist ctx.save 和 ctx.restore ?为什么这里需要它?

JS小提琴

        function recolor(color) {
        ctx.save();
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(pic, 0, 0);
        ctx.globalCompositeOperation = "source-in";
        ctx.fillStyle = color;
        ctx.rect(0, 0, canvas.width, canvas.height);
        ctx.fill();
        ctx.restore();
        var img = new Image();
        img.src = canvas.toDataURL();
        return (img);
    }
4

2 回答 2

2

save用于保存和restore恢复所有上下文状态,如fillStylelineWidthglobalCompositeOperation、裁剪区域、当前上下文变换矩阵等。

save和在你的小提琴中唯一必要的目的restore是重置globalCompositeOperation.

您可以手动执行此操作:

    function recolor(color) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(pic, 0, 0);
        ctx.globalCompositeOperation = "source-in";
        ctx.fillStyle = color;
        ctx.rect(0, 0, canvas.width, canvas.height);
        ctx.fill();

        //instead of save and restore:
        ctx.globalCompositeOperation = "source-over";

        var img = new Image();
        img.src = canvas.toDataURL();
        return (img);
    }

一般来说,除非绝对必须,否则应避免使用saveand ,因为它的计算成本很高。restore

于 2013-06-25T17:09:45.483 回答
0

ctx save 和 restore 用于保存当前上下文状态。这通常用于函数中,以便您可以在任何地方调用它们,而不必担心它会改变函数外部的绘制状态。

例如,在这段代码中,您更改了 fillStyle。调用 ctx.restore 后,填充样式将恢复为调用 ctx.save 时的样式。

于 2013-06-25T14:13:46.430 回答