如何保存和回复canvas状态

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    function draw(){
        //获取js对象
        var c=document.getElementById("mycanvas");
        //设置大小
        c.height=800;
        c.width=800;
        //获取用户画图的2d的环境
        var ctx=c.getContext("2d");
        //画一个矩形
        //设置填充颜色
        ctx.fillStyle="#ff0000";
        //设置矩形边框颜色
        ctx.strokeSytl="#000000";
        //绘制
        ctx.fillRect(20,20,200,100);
        ctx.strokeRect(20,20,200,100);
        ctx.fill();
        ctx.stroke();
        //将上面的状态保存起来,可以使用restore提取出来
        ctx.save();
        
        
        //在画一个
        ctx.fillStyle="#ff00ff";
        ctx.strokeSyle="#0000ff";
        ctx.fillRect(200,200,100,50);
        ctx.strokeRect(200,200,100,50);
        ctx.fill();
        ctx.stroke();
        
        //恢复状态
        ctx.restore();
        //再话一个矩形
        ctx.fillRect(300,300,100,100);
        ctx.strokeRect(300,300,100,100);
        
    }
        
</script>
</head>
<body>
    <canvas id="mycanvas"></canvas>
    <input type="button" value="画图" onclick="draw();"/>
</body>
</html>

 

 

 

posted on 2017-05-18 17:19  河狸筑坝  阅读(128)  评论(0编辑  收藏  举报