js+canvas 实现移动端的签名

效果图

下载地址:链接:https://pan.baidu.com/s/12AM4jxCQDSOHnFawdzqa6A 密码:ws3a

function signatureCanvas(p) {
    var defaults = {
        wrapperEl: document.getElementById("signature_wrapper"),
        clearBtnEl: document.getElementById("clear_canvas"),
        saveBtnEl: document.getElementById("save_canvas"),
        strokeStyle: "#000",
        linewidth: 1,
        background: "#fff",
        border: '0 none'
    };
    for (var property in p) {
        defaults[property] = p[property]
    }
    var params = defaults;
    var wrapperEl = params.wrapperEl;
    var clearBtnEl=params.clearBtnEl;
    var saveBtnel =params.saveBtnEl;
    var canvas = document.createElement('canvas');
    console.log(canvas)
    wrapperEl.appendChild(canvas);
    canvas.style.display = 'block';
    canvas.width = (params.width) ? (params.width) : (wrapperEl.offsetWidth);
    canvas.height = (params.height) ? (params.height) : (wrapperEl.offsetWidth);
    ctxOffsetTop=canvas.offsetTop;
    ctxOffsetLeft=canvas.offsetLeft;
    var ctx = canvas.getContext('2d');
    ctx.strokeStyle = params.strokeStyle;
    ctx.lineWidth = params.linewidth;
    ctx.fillStyle = params.background;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    canvas.addEventListener('touchstart',function (e) {
        console.log('touchstart')
        ctx.beginPath();
        ctx.moveTo(e.changedTouches[0].pageX-ctxOffsetLeft, e.changedTouches[0].pageY-ctxOffsetTop);
        return false;
    });
    canvas.addEventListener('touchmove',function (e) {
        e.preventDefault()
        console.log('touchmove')
        ctx.lineTo(e.changedTouches[0].pageX-ctxOffsetLeft, e.changedTouches[0].pageY-ctxOffsetTop);
        ctx.stroke();
        return false;
    });
    canvas.addEventListener('touchend',function (e) {
        console.log('touchend')
        ctx.closePath();
        return false;
    });
    clearBtnEl.addEventListener('click',function (e) {
        ctx.clearRect(0, 0, canvas.width, canvas.height)
    });
    saveBtnel.addEventListener('click',function (e) {
        var imgBase64 = canvas.toDataURL()
        console.log(imgBase64)
    })

}

最后保存的图片是base64 var imgBase64 = canvas.toDataURL()

你可能感兴趣的:(js+canvas 实现移动端的签名)