html+canvas 实现签名功能-鼠标

运行效果

image

代码样例

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .buttons {
            margin-top: 10px;
        }
    </style>
</head>

<body>
    <div>
        <canvas id="signatureCanvas" width="500" height="200" style="border:solid;"></canvas>
        <button onclick="clearSignature()">清除</button>
        <button onclick="undoLast()">清除上一步</button>
        <button onclick="saveSignature()">保存</button>
    </div>
    <script>
        const canvas = document.getElementById('signatureCanvas');
        const ctx = canvas.getContext('2d');

        let isDrawing = false;
        let lastX, lastY;
        let strokes = []; // 用于存储每一步的绘制操作

        // 鼠标按下事件
        function handleMouseDown(e) {
            isDrawing = true;
            [lastX, lastY] = [e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop];
            strokes.push([]); // 开始新的笔画
        }

        // 鼠标移动事件
        function handleMouseMove(e) {
            if (!isDrawing) return; // 如果鼠标没有按下,则退出函数

            const x = e.clientX - canvas.offsetLeft;
            const y = e.clientY - canvas.offsetTop;

            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(x, y);
            ctx.stroke();

            strokes[strokes.length - 1].push({ x: lastX, y: lastY, x2: x, y2: y }); // 记录当前笔画

            [lastX, lastY] = [x, y];
        }

        // 鼠标释放事件
        function handleMouseUp() {
            isDrawing = false;
        }

        // 清除签名
        function clearSignature() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            strokes = []; // 清空所有笔画记录
        }

        // 撤销上一步
        function undoLast() {
            strokes.pop(); // 移除最后一个笔画
            redraw(); // 重新绘制画布
        }

        // 重新绘制画布
        function redraw() {
            ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布
            strokes.forEach(stroke => {
                stroke.forEach(line => {
                    ctx.beginPath();
                    ctx.moveTo(line.x, line.y);
                    ctx.lineTo(line.x2, line.y2);
                    ctx.stroke();
                });
            });
        }

        // 保存签名
        function saveSignature() {
            const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);

            // 将图片数据转换成 base64 格式
            const base64ImageData = canvas.toDataURL();
            console.log(base64ImageData);
        }

        // 绑定事件
        canvas.addEventListener('mousedown', handleMouseDown);
        canvas.addEventListener('mousemove', handleMouseMove);
        canvas.addEventListener('mouseup', handleMouseUp);
        canvas.addEventListener('mouseout', handleMouseUp);
    </script>
</body>

</html>

posted @ 2024-07-18 11:10  darling331  阅读(11)  评论(0编辑  收藏  举报