美文网首页canvas
canvas 画笔功能

canvas 画笔功能

作者: 谢炳南 | 来源:发表于2022-08-22 11:24 被阅读0次

效果图

微信截图_20220822112416.png
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style>
            #canvas {
                border: 1px solid red;
            }
        </style>
    </head>
    <body>
        <canvas id="canvas" width="800" height="800"></canvas>
    </body>
</html>
<script>
    // 线条宽度
    let strokeWidth = 5;
    // 线条颜色
    let strokeColor = 'red';
    
    let canvas = document.getElementById('canvas');
    let ctx = canvas.getContext('2d');
    // 线条末端添加圆形线帽,减少线条的生硬感
    ctx.lineCap = 'round';
    // 当两条线条交汇时,创建圆形边角
    ctx.lineJoin = 'round';
    ctx.lineWidth = strokeWidth;
    ctx.strokeStyle = strokeColor;
    // 利用阴影,消除锯齿
    ctx.shadowBlur = 1;
    ctx.shadowColor = strokeColor;
    
    let drawStatus = false;
    
    canvas.addEventListener('mousedown', function(e){
        drawStatus = true;
        ctx.moveTo(e.offsetX, e.offsetY);
        startX = e.offsetX;
        startY = e.offsetY;
    });
    
    canvas.addEventListener('mousemove', function(e) {
        if (!drawStatus) {
            return;
        }
        ctx.lineTo(e.offsetX, e.offsetY);
        ctx.stroke();
    })
    
    canvas.addEventListener('mouseup', function(e) {
        drawStatus = false;
        console.log('out');
    })
</script>

相关文章

网友评论

    本文标题:canvas 画笔功能

    本文链接:https://www.haomeiwen.com/subject/hcligrtx.html