Canvas实现简单画板(canvas学习二)

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>
</head>
<body>
    <canvas id="canvas" width="400" height="400" ></canvas>
</body>
<script>
    var flag = false;
    //获得画布元素
    var canvas = document.getElementById("canvas");
    //获得二维绘图对象
    var ctx = canvas.getContext("2d");
    //设置线宽
    ctx.lineWidth = '2';
    //颜色
    ctx.color = 'red';
    // 循环触发
    // canvas.onmousemove = function (e){
    //     console.log(e);
    //     ctx.lineTo(e.clientX,e.clientY);
    //     ctx.fill();
    //     ctx.fillStyle = 'red';
    //     ctx.stroke();//执行绘制线条
    // }
    canvas.onmousedown = (e)=>{
        console.log("down");
        flag = true;
    }
    canvas.onmouseup = (e)=>{
        flag = false;
        console.log("up");
    }
    canvas.onmousemove = (e)=>{
        console.log("move");
        if(!flag) return;
        ctx.lineTo(e.clientX,e.clientY);
        // ctx.fillStyle = 'red';
        // ctx.fill();
        ctx.stroke();//执行绘制线条
    }
</script>
</html>

猜你喜欢

转载自blog.csdn.net/qq_38880700/article/details/89077320