javascript - Canvas 裁剪区域和 Canvas 堆栈

标签 javascript html canvas html5-canvas

我已经开始阅读 O'Reilly 的书“HTML5 Canvas”。我在第二章中,其中一个示例提供了没有很好解释的代码。示例 2-5:

  1. 画一个黑框
  2. 推送状态
  3. 在左上角设置小裁剪区域
  4. 画圆
  5. 弹出状态
  6. 设置大裁剪区域
  7. 再画一个圆

但我无法理解某些事情:

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

第二,为什么要推送上下文状态?为什么我不能只更改剪辑区域?这似乎是必要的,因为如果不插入状态,它是行不通的。如果我不推送状态然后恢复它,蓝色大圆圈不会出现,我不明白为什么。

最佳答案

Does context.clip() implicitly close the context path ?...
It is preceded by a context.beginPath(), and followed by another context.beginPath(). Like this: [...]

是的,这是创建剪切所需的闭合形状的唯一方法,因此如果未调用 closePath(),则 clip() 将在内部关闭路径。

specification states:

Open subpaths must be implicitly closed when computing the clipping region, without affecting the actual subpaths.

beginPath() 将清除当前主路径及其所有子路径。虽然裁剪仍然处于事件状态,但现在您可以执行其他路径操作,这些操作将在光栅化时受到裁剪区域的影响。

Why is it necessary to push the context state?

虽然有人建议和讨论过,但无法重置剪辑区域(标准中有一个 resetClip(),但尚未得到广泛支持)。 Calling clip()好几次-

The clip() method must create a new clipping region by calculating the intersection of the current clipping region [...]

换句话说,如果我们说为整个绘图表面定义了一个剪辑区域,它不会被替换。

所以我们可以删除剪辑的唯一方法是保存状态,设置剪辑然后恢复以删除它。

关于javascript - Canvas 裁剪区域和 Canvas 堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37212846/

相关文章:

java - 使用 SWT 进行快速像素绘图?

javascript - 是否可以在 Node js 中操作 DOM?

javascript - JavaScript 的 Pep-8 样式指南

javascript - 如何通过标签 "selected"改变背景图片

javascript - HTML5 - Canvas 失去焦点?

Javafx:用鼠标在ImageView上绘图

java - 使用 javascript 动态添加行时,我增加索引值,但出现错误

javascript - 绑定(bind)到滚轮然后使用正常滚动

javascript - 解码音频数据 - 无法解码音频数据

html - 为什么我的页面不可滚动?