思路:

原生javascript-移动端手写签名_JavaScript

效果:

原生javascript-移动端手写签名_JavaScript_02

<html>

<head>

    <style>

        * {

            margin: 0px;

            padding: 0px;

        }

        

        canvas {

            border: 1px solid black;

        }

    </style>

    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />

</head>

 

<body>

    <canvas id="canvas" width="500px" height="500px"></canvas>

    <script>

        // 获取canvas对象

        var canvas = document.getElementById("canvas");

        // 获取canvas上下文

        var cxt = canvas.getContext("2d");

        // 定义鼠标按下为false

        var ISmousedown = false;

        // 监听鼠标按下

        canvas.addEventListener("mousedown", function(e) {

                // 获取在canvas上的x,y轴坐标

                var x = e.layerX;

                var y = e.layerY;

                // 设置鼠标按下为false

                ISmousedown = true;

                // 开始一条路径

                cxt.beginPath();

                // 把路径移动到画布中的指定点

                cxt.moveTo(x, y);

            }, false)

            // 监听鼠标移动

        canvas.addEventListener("mousemove", function(e) {

                // 在鼠标按下时有效

                if (ISmousedown) {

                    // 获取在canvas上的x,y轴坐标

                    var x = e.layerX;

                    var y = e.layerY;

                    // 设置线条的颜色

                    cxt.strokeStyle = "green";

                    // 添加一个新点,然后在画布中创建从该点到最后指定点的线条

                    cxt.lineTo(x, y);

                    // 在画布上绘制确切的路径

                    cxt.stroke();

                }

            }, false)

            // 监听鼠标抬起

        canvas.addEventListener("mouseup", function() {

            // 设置鼠标抬起为false

            ISmousedown = false;

        }, false)

    </script>

</body>

 

</html>