用canvas實(shí)現(xiàn)簡易的畫布效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        
        canvas{
            border:1px solid #ccc;
        }
        #box{
            display: inline-block;
            width: 20px;
            height: 20px;
            background: yellow;
        }
        #nul{
            display: inline-block;
            margin-left: 10px;
            font-size: 12px;
            text-align: center;
            width: 40px;
            height: 20px;
            background: pink;
        }
    </style>
</head>
<body>
    <div id="box"></div>
    <div id="nul">清除</div><br>
    <canvas id="mycanvas">您的破瀏覽器不兼容
    </canvas>
            
    <script>
        
        var canvas = document.getElementById("mycanvas");
        var box = document.getElementById("box");
        var nul = document.getElementById("nul");

        //設(shè)置寬高
        canvas.width = 500;
        canvas.height = 500;

        //獲取繪圖環(huán)境
        var cxt = canvas.getContext("2d");

        //鼠標(biāo)按下
        canvas.onmousedown = function(e){
            //鼠標(biāo)在 畫布上的位置
            var x = e.clientX - canvas.offsetLeft;
            var y = e.clientY - canvas.offsetTop;
            cxt.beginPath();
            cxt.moveTo(x, y);
            console.log("mousedown");

            //鼠標(biāo)移動
            canvas.onmousemove = function(e){
                var x = e.clientX - canvas.offsetLeft;
                var y = e.clientY - canvas.offsetTop;
                cxt.lineTo(x, y);
                cxt.stroke();
            }
                        //點(diǎn)擊box改變畫筆顏色 
            box.onclick=function(){
                cxt.strokeStyle = "yellow";
            }
                        //點(diǎn)擊nul清空畫布
            nul.onclick=function(){
                    cxt.clearRect(0,0,500,500);
                }

            //鼠標(biāo)抬起事件
            canvas.onmouseup = function(){
                canvas.onmousemove = null;
            }

            
        }


    </script>
</body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容