canvas--画板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #out{
            border: 1px solid red;
        }
    </style>
</head>
<body>
    <canvas id="out" height="500" width="500"></canvas>
    <button id="huihua">绘画</button>
    <button id="cachu">橡皮擦</button>
    <button id="chongzhi">重置</button>
</body>
<script>
    var cvs = document.getElementById("out")
    var huihua = document.getElementById("huihua")
    var cachu = document.getElementById("cachu")
    var chongzhi = document.getElementById("chongzhi")
    var ctx = cvs.getContext("2d")
    chongzhi.onclick = function(){
        ctx.clearRect(0,0,cvs.width,cvs.height)
    }

    cachu.onclick=function(){
        cvs.onmousedown=function(){
            document.onmousemove=function(e){
                ctx.clearRect(e.clientX-cvs.offsetLeft,e.clientY-cvs.offsetTop,20,20)
            }
            document.onmouseup=function(){
                document.onmousedown=null;
                document.onmousemove=null;
            }
        }
    }

    huihua.onclick = function () {
        cvs.onmousedown=function(e){
             ctx.beginPath()
             ctx.moveTo(e.clientX-cvs.offsetLeft,e.clientY-cvs.offsetTop)
             document.onmousemove=function(e){
                 ctx.lineTo(e.clientX-cvs.offsetLeft,e.clientY-cvs.offsetTop)
                 ctx.strokeStyle="red"
                 ctx.stroke()
             }
             document.onmouseup=function(){
                 document.onmousedown=null;
                 document.onmousemove=null;
             }
        } 
    }

    
</script>
</html>

猜你喜欢

转载自blog.csdn.net/qq_42697338/article/details/86548886