前端H5用Canvas画布做类似银行签名的操作

前端H5用Canvas画布做类似银行签名的操作_第1张图片




    
    签名页面





签名预览


// 获取Canvas元素
const canvas = document.getElementById("signatureCanvas");
const ctx = canvas.getContext("2d");

// 设置绘制参数
ctx.strokeStyle = "#000"; // 线条颜色
ctx.lineWidth = 2; // 线条宽度

// 标记签名是否开始
let drawing = false;

// 监听鼠标按下事件
canvas.addEventListener("mousedown", (e) => {
    drawing = true;
    ctx.beginPath();
    ctx.moveTo(e.clientX - canvas.getBoundingClientRect().left, e.clientY - canvas.getBoundingClientRect().top);
});

// 监听鼠标移动事件
canvas.addEventListener("mousemove", (e) => {
    if (drawing) {
        ctx.lineTo(e.clientX - canvas.getBoundingClientRect().left, e.clientY - canvas.getBoundingClientRect().top);
        ctx.stroke();
    }
});

// 监听鼠标松开事件
canvas.addEventListener("mouseup", () => {
    drawing = false;
});

// 清除签名
document.getElementById("clearButton").addEventListener("click", () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    document.getElementById("signatureImage").src = "";
});

// 保存签名
document.getElementById("saveButton").addEventListener("click", () => {
    const signatureImage = document.getElementById("signatureImage");
    signatureImage.src = canvas.toDataURL("image/png");
});

你可能感兴趣的:(前端,前端,javascript,开发语言)