HTML5 Cavans(4) 保存和恢复Cavans状态

本文介绍HTML5 Canvas中如何使用save和restore方法管理绘图状态,包括颜色、线宽等属性,并提供了完整的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

复制代码
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title></title>
    <script type="text/javascript">
        window.onload = function () {

            var cancans = document.getElementById("myCanvas");
            //得到2D渲染上下文
            var context = document.getElementById("myCanvas").getContext("2d");

            context.fillRect(0, 0, 100, 100);
            context.fillStyle = "red";
            context.fillRect(0, 0, 50, 50);

            DisplayColor();
            document.getElementById("btnRestore").onclick = function () {
                context.restore();
                DisplayColor();
                alert("RestoredColor:" + context.fillStyle);
            };

            document.getElementById("btnDraw").onclick = function () {
                context.fillRect(0, 0, 50, 50);
            };

            document.getElementById("btnSetColor").onclick = function () {
                var color = document.getElementById("txtColor").value;
                context.fillStyle = color;
                DisplayColor();
            };
            document.getElementById("btnSave").onclick = function () {
                context.save();
                alert("SavedColor:" + context.fillStyle);
            };

            function DisplayColor() {
                document.getElementById("spancolor").innerHTML = context.fillStyle;
            }
        };
    </script>
</head>
<body>
    <input type="button" id="btnRestore" value="Restore" >
    <input type="button" id="btnSave" value="Save" >
    <input type="button" id="btnDraw" value="Draw" >
    <input type="button" id="btnSetColor" value="SetColor" >
    <input type="text" id="txtColor" >
    <span>currentColor:</span><span id="spancolor"></span>
    <canvas id="myCanvas" height="300px" width="500px">
    </canvas>
</body>
</html>
复制代码

 

对2d渲染上下文调用save方法保存当前状态,restore方法恢复状态,状态是线宽,颜色等属性,不包括画出的图形

每次save都会把当前状态存入绘图栈,每次restore方法把绘图栈最晚进的取出设置为当前状态

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值