html5怎么恢复默认,存储和恢复HTML5Canvas状态

当我们在 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);

下图是采用以上代码的绘制结果:

0w3hchrhkbo.gif

如果你频繁的做各种复杂的绘图设置时,状态堆栈是相当有用的。

所有的 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())

这个列表并不完整,还不包含一些标准的属性。

Source: http://tutorials.jenkov.com/html5-canvas/state.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值