English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML5 Canvas Zustand

Wir ändern beim Zeichnen von Graphiken auf dem Canvas oft den Zustand durch save() und restore().2Der Status des D-Kontexts. Zum Beispiel benötigen Sie eine bestimmte strokeStyle, wenn Sie eine Linie oder ein Rechteck zeichnen, und eine andere strokeStyle für die nächste Linie oder das nächste Rechteck. Oder unterschiedliche Farben für die Füllung, Winkel der Rotation usw.


Wenn Sie ihn2Der D-Kontext in HTML5Wenn Sie auf dem Canvas zeichnen, dieser2Der D-Kontext ist in einem bestimmten Zustand. Sie können den Zustand durch Manipulation2Die Attribute des D-Kontexts (z.B. fillStyle und strokeStyle) zum Setzen dieses Status. Alle diese Operationen werden gemeinsam als2Der State des D-Kontexts.
Normalerweise müssen Sie den Status während des Zeichnens auf dem Canvas ändern.2Der Status des D-Kontexts. Zum Beispiel benötigt strokeStyle für eine Linie oder einen Rechteck, während er für andere Linien oder Rechtecke möglicherweise einen anderen benötigt. Oder andere Wechsel, oder andere.
由于在绘制每个形状之前设置完整状态非常麻烦,因此可以将状态推送到状态堆栈上。然后可以从此状态堆栈中弹出较早的状态。这是在临时状态更改后恢复较早状态的快速方法。

HTML5 Canvas画布状态示例

绘图状态进行压栈和出栈的方法如下:

context.save();     // 将一个状态压入状态栈中.
context.restore();  // 将最前面的状态出栈,并设置到2d上下文中.

被保存在堆栈中后,您可以将多个状态推送到该堆栈上,然后将其弹出。这是一个代码示例:

<canvas id="ex1" width="500" height="100" style="border: 1px fest #cccccc;">HTML5 Canvas nicht unterstützt</canvas>
<script>
var canvas  = document.getElementById("ex1");
var context = canvas.getContext("2d");
context.fillStyle  ="#66ff66";
context.strokeStyle="#990000";
context.lineWidth  = 5;
context.fillRect  (5, 5, 50, 50);
context.strokeRect(5, 5, 50, 50);
context.save();
context.fillStyle = "#6666ff";
context.fillRect  (65, 5, 50, 50);
context.strokeRect(65, 5, 50, 50);
context.save();
context.strokeStyle = "#000099";
context.fillRect  (125, 5, 50, 50);
context.strokeRect(125, 5, 50, 50);
context.restore();
context.fillRect  (185, 5, 50, 50);
context.strokeRect(185, 5, 50, 50);
context.restore();
context.fillRect  (245, 5, 50, 50);
context.strokeRect(245, 5, 50, 50);
</script>
测试看看 ‹/›

这是在画布上绘制时上述代码的结果:

HTML5 Canvas nicht unterstützt

状态栈的用处

如果您更改画布合成模式或转换设置,并且需要在进行更改之前先返回到设置,则状态堆栈非常有用。通过保存和恢复构图模式或转换设置,可以确保正确重置了它。否则,要返回到之前的确切设置可能会有些困难。

2D上下文的状态有哪些?

所有2D上下文属性都是保存和还原状态的一部分。但是,在画布上绘制的却不是。这意味着,在还原状态时,您不会还原绘图区域本身。您仅还原2D上下文设置(属性值)。这些设置包括:

  • fillStyle

  • font

  • globalAlpha

  • globalCompositionOperation

  • lineCap

  • lineJoin

  • lineWidth

  • miterLimit

  • shadowBlur

  • shadowColor

  • shadowOffsetX

  • shadowOffsetY

  • strokeStyle

  • strokeStyle

  • textAlign

  • textBaseline

  • Der Ausschnittsbereich

  • Die Transformationsmatrix (durch context.rotate())+ Drehung+Verschiebung context.setTransform())

Diese Liste ist nicht vollständig. Mit der Entwicklung des Standards könnten mehr Attribute2Ein Teil des Context-Status.