javascript - 为什么在给这个图像着色时使用保存和恢复?

标签 javascript canvas

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

JS FIDDLE

        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);
    }

最佳答案

saverestore 用于保存和恢复所有上下文状态,例如fillStyle, lineWidth, globalCompositeOperation、裁剪区域、当前上下文变换矩阵等。

saverestore 在你的 fiddle 中的唯一必要目的是重置 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);
    }

一般情况下,您应该避免使用saverestore,除非您绝对必须这样做,因为它的计算成本会很高。

关于javascript - 为什么在给这个图像着色时使用保存和恢复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17299637/

相关文章:

Javascript window.open 不工作

css - html 在不拉伸(stretch) Canvas 的情况下在 div 中居中 Canvas

android - 在 Canvas 上绘制文本不适用于可变位图

html - 为什么 38px x 38px 比 Canvas 矩形 38 x 38 大,尽管尺寸相同 >

javascript - 再次将 Canvas 像素设置为透明

javascript - 如何使 Backbone 中的 JQuery 进度栏显示多个 Ajax 调用的进度?

javascript - 如何在jquery上的set Interval函数中添加 '' this''

javascript - queryselectorAll() 与正则表达式属性选择器

javascript - 是否可以在浏览器中使用 javascript 对用户系统进行基准测试

javascript - 从 HTML Canvas 中提取的 ArrayBuffer 与使用 UTIF 解码并加载到其上的 ArrayBuffer 不同