存儲和恢復 HTML5 Canvas 狀態
當我們在 HTML5 Canvas 上使用其 2D 上下文進行圖形繪制的時候,可以通過操作 2D 上下文的屬性來繪制不同風格的圖形,例如不同字體、填充等等。
通常情況下,在畫布上的繪圖時,您需要更改在繪制的2D背景下的狀態。例如,你可能需要一個strokStyle 一行或矩形,另有其他行或矩形strokeStyle。或不同的旋轉,或別的東西。
設置繪圖的屬性非常繁瑣,每次更改時都要從來一次,本文將介紹如何利用堆棧來保持繪圖的屬性并在需要的時候隨時恢復。例如我們可以通過下面兩個方法來實現保存繪圖屬性和獲取屬性:
context.save(); // state pushed onto stack. context.restore(); // state popped from stack, and set on 2D Context.
你可以保持多個繪圖屬性到堆棧中,并在需要的時候從堆棧中彈出:
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);
下圖是采用以上代碼的繪制結果:

如果你頻繁的做各種復雜的繪圖設置時,狀態堆棧是相當有用的。
所有的 2D 繪圖上下文屬性都是可保存和恢復的屬性,但繪制的內容可不是,也就是說你恢復了繪圖上下文,并不會恢復其所繪制的圖形。
2D 繪圖上下文包括如下設置:
- fillStyle
- font
- globalAlpha
- globalCompositionOperation
- lineCap
- lineJoin
- lineWidth
- miterLimit
- shadowBlur
- shadowColor
- shadowOffsetX
- shadowOffsetY
- strokeStyle
- strokeStyle
- textAlign
- textBaseline
- The clipping region
- The transformation matrix (rotations + translations via context.rotate() + context.setTransform())
這個列表并不完整,還不包含一些標準的屬性。
本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!