canvas绘制线条&canvas实现写字板功能

canvas画V

var canvas = document.querySelector("canvas");
        var ctx = canvas.getContext("2d");
        ctx.strokeStyle = "red";
        //线粗细
        ctx.lineWidth = 10;
        //线两端弧化
        ctx.lineCap = "round";
        //线拐点弧化
        ctx.lineJoin = "round";
        ctx.beginPath();
        //笔头移动到位置
        ctx.moveTo(50,50);
        //划线
        ctx.lineTo(100,100);
        ctx.lineTo(150,50);
        //笔头移动到位置
        ctx.moveTo(200,50);
        ctx.lineTo(250,100);
        ctx.lineTo(300,50);
        //展示,填充笔触
        ctx.stroke();
    </script>

canvas绘制线条&canvas实现写字板功能

canvas写字板

var canvas = document.querySelector("canvas");
        var ctx = canvas.getContext("2d");
        ctx.strokeStyle = "red";
        //线粗细
        ctx.lineWidth = 10;
        //线两端弧化
        ctx.lineCap = "round";
        //线拐点弧化
        ctx.lineJoin = "round";
        document.addEventListener("mousedown", mouseHandler);
        function mouseHandler(e) {
            switch (e.type) {
                case ‘mousedown‘:
                    //起始绘制位置
                    ctx.moveTo(e.clientX, e.clientY);
                    document.addEventListener("mousemove", mouseHandler);
                    document.addEventListener("mouseup", mouseHandler);
                    break;
                case ‘mousemove‘:
                    ctx.lineTo(e.clientX, e.clientY);
                    ctx.stroke();//画出来
                    break;
                case ‘mouseup‘:
                    document.removeEventListener("mousemove", mouseHandler);
                    document.removeEventListener("mouseup", mouseHandler);
                    break;
            }
        }

 效果:

canvas绘制线条&canvas实现写字板功能