我发现这段代码可以为 Canvas 图像文件着色。我想知道 ist ctx.save 和 ctx.restore 在此着色上下文中的用途是什么?为什么这里需要它?
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);
}
最佳答案
save
和restore
用于保存和恢复所有上下文状态,例如fillStyle
, lineWidth
, globalCompositeOperation
、裁剪区域、当前上下文变换矩阵等。
save
和 restore
在你的 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);
}
一般情况下,您应该避免使用save
和restore
,除非您绝对必须这样做,因为它的计算成本会很高。
关于javascript - 为什么在给这个图像着色时使用保存和恢复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17299637/