【发布时间】:2016-05-13 14:36:55
【问题描述】:
我已经开始阅读 O'Reilly 的书“HTML5 Canvas”。我在第二章,其中一个示例提供的代码解释得不是很好。示例 2-5:
- 画一个黑盒子
- 推送状态
- 在左上角设置小剪辑区域
- 画圆
- 弹出状态
- 设置大的剪辑区域
- 再画一个圆圈
但我无法理解一些事情:
context.fillStyle = 'black';
context.fillRect(10, 10, 200, 200);
context.save();
context.beginPath();
context.rect(0, 0, 50, 50);
context.clip();
context.beginPath();
context.strokeStyle = 'red';
context.lineWidth = 5;
context.arc(100, 100, 100, 0, 2*Math.PI, false);
context.stroke();
context.closePath();
context.restore();
context.beginPath();
context.rect(0, 0, 500, 500);
context.clip();
context.beginPath();
context.strokeStyle = 'blue';
context.lineWidth = 5;
context.arc(100, 100, 50, 0, 2*Math.PI, false);
context.stroke();
context.closePath();
我的问题:
首先,context.clip() 是否隐式关闭上下文路径(“context.closePath()”)?它前面是一个 context.beginPath(),后面是另一个 context.beginPath()。像这样:
context.beginPath();
context.rect(0, 0, 50, 50);
context.clip();
context.beginPath();
第二,为什么要推送上下文状态?为什么我不能只更改剪辑区域?这似乎是必要的,因为不推动状态它是行不通的。如果我不推送状态然后恢复它,蓝色大圆圈不显示,我不明白为什么。
【问题讨论】:
-
beginPath 开始一个全新的路径并转储旧路径。 closePath 与 beginPath 无关。 ClosePath 只需创建一个从当前位置到最后一个 moveTo 位置的 lineTo 您可以拥有任意数量的 closePath,每个渲染输出只能有一个 beginPath(stroke()、fill())。剪辑是累积的,每次添加剪辑都会被前一个剪辑剪辑,每个剪辑区域越来越小。要恢复,您必须使用保存和恢复。
标签: javascript html canvas html5-canvas