小言_互联网的博客

如何存储和恢复 HTML5 Canvas 状态

428人阅读  评论(0)

当我们在 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())
这个列表并不完整,还不包含一些标准的属性。

 


转载:https://blog.csdn.net/weixin_39037804/article/details/101028218
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场