搜索
javascript - 清除Canvas问题
天蓬老师
天蓬老师 2017-04-10 16:23:38
[JavaScript讨论组]
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body style="background: black;">
        <canvas id="c1" width="300px" height="300px" style="background-color: #fff;"></canvas>
        <br /><input type="button" name="" id="inp" value="清空" />
        <script type="text/javascript">
            var oC1=document.getElementById("c1");
            var oInp=document.getElementsByTagName("input")[0];
            var oGC=oC1.getContext("2d");
            oGC.fillStyle="#FF0000";
            oGC.strokeStyle="#000";
            oC1.onmousedown=function(ev){
                oGC.clearRect(0,0,oC1.width,oC1.height);
                var ev=ev||event;
                oGC.moveTo(ev.clientX-oC1.offsetLeft,ev.clientY-oC1.offsetTop);
                document.onmousemove=function(ev){
                    var ev=ev||event;
                    oGC.lineTo(ev.clientX-oC1.offsetLeft,ev.clientY-oC1.offsetTop);
                    oGC.stroke();
                }
                document.onmouseup=function () {
                    document.onmousemove=null;
                }
            }
            oInp.onclick=function  () {
                oGC.clearRect(0,0,oC1.width,oC1.height);
            }
        </script>
    </body>
</html>

点击按钮后清除画布,再一次画图,之前的图像又跑出来了,求解决

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(2)
PHP中文网

oGC.moveTo 前先 oGC.beginPath()

不然你的 moveTolineTo 会一直留在默认 path 里。

ringa_lee
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body style="background: black;">
<canvas id="c1" width="300px" height="300px" style="background-color: #fff;"></canvas>
<br /><input type="button" name="" id="inp" value="清空" />
<script type="text/javascript">
    var oC1=document.getElementById("c1");
    var oInp=document.getElementsByTagName("input")[0];
    var oGC=oC1.getContext("2d");
    oGC.fillStyle="#FF0000";
    oGC.strokeStyle="#000";
    oC1.onmousedown=function(ev){
        //oGC.clearRect(0,0,oC1.width,oC1.height);
        var ev=ev||event;
        oGC.beginPath();//结束上一次路径绘制,开始一个新路径绘制
        oGC.moveTo(ev.clientX-oC1.offsetLeft,ev.clientY-oC1.offsetTop);
        document.onmousemove=function(ev){
            var ev=ev||event;
            oGC.lineTo(ev.clientX-oC1.offsetLeft,ev.clientY-oC1.offsetTop);
            oGC.stroke();
        }
        document.onmouseup=function () {
            document.onmousemove=null;
        }
    }
    oInp.onclick=function  () {
        oGC.clearRect(0,0,oC1.width,oC1.height);
    }
</script>
</body>
</html>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号