canvas 保存、恢复状态(转)
原文地址:http://www.cnblogs.com/LittleBai/p/5989949.html
1.保存和恢复绘图状态:
在绘制图形时,难免会重复使用某个样式,甚至有时会在不同颜色之间来回切换。
那么为了减少代码冗余,我们可以调用画布中的save()方法,来帮我们
保存一些样式和属性,这样我们就可以再通过调用restore() 方法,来再次使用这些我们曾保存好的样式和属性了!
下面看下具体代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>保存和恢复绘图状态</title>
<script type="text/javascript">
window.onload = function () {
//保存绘图状态 save
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "rgb(255,0,0)";
context.save(); //保存状态
context.fillRect(50, 50, 100, 100); //初始定义,绘制红色矩形
//恢复绘图状态 restore
context.fillStyle = "rgb(0,255,0)";
context.fillRect(200, 50, 100, 100); //绘制绿色矩形
context.restore(); //恢复画布状态
context.fillRect(350, 50, 100, 100); //恢复到初始定义,绘制红色矩形
}
</script>
</head>
<body>
<canvas id="myCanvas" width="1000" height="1000">
您的浏览器暂不支持画布!
</canvas>
</body>
</html>2.保存和恢复多个绘图状态:
多个绘图状态是如何保存的呢?
我们可以这么理解:有台复印机在大量的复印资料,最先复印的肯定是在最下层的,后来的一张张的累在上面,然后堆成一摞儿,
最上面的那份肯定是最后一次的复印操作,这个毋庸置疑!
保存状态其实就类似复印机的工作状态,最近保存的在最上层!
来看下代码怎么实现:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>保存和恢复绘图状态</title>
<script type="text/javascript">
window.onload = function () {
//保存绘图状态 save
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "rgb(255,0,0)";
context.save();
context.fillRect(50, 200, 100, 100); //第一个保存状态,绘制红色矩形
context.fillStyle = "rgb(0,0,255)";
context.save();
context.fillRect(200, 200, 100, 100); //第二个保存状态,绘制蓝色矩形
context.restore();
context.fillRect(350, 200, 100, 100); //恢复蓝色矩形的保存状态,因为它是最后的保存状态,所以它最先恢复。
context.restore();
context.fillRect(500, 200, 100, 100); //恢复红色矩形的保存状态。
}
</script>
</head>
<body>
<canvas id="myCanvas" width="1000" height="1000">
您的浏览器暂不支持画布!
</canvas>
</body>
</html>相关推荐
jinxiutong 2020-05-10
MIKUScallion 2020-02-22
songfens 2020-01-10
大地飞鸿 2020-11-12
星星有所不知 2020-10-12
jinxiutong 2020-07-26
MIKUScallion 2020-07-05
songfens 2020-07-05
songfens 2020-06-11
songfens 2020-06-08
northwindx 2020-05-31
northwindx 2020-05-31
northwindx 2020-05-27
northwindx 2020-05-25
MIKUScallion 2020-05-25
xdyangxiaoromg 2020-05-10
大地飞鸿 2020-05-06