html5 运用canvas笔写签字并储存的完成方式

日期:2020-10-13 类型:科技新闻 

关键词:如何制作微信小程序,微信小程序源码,小程序码生成,凡科网微信小程序,微信公众号小程序

近期企业在做1个签字的作用,关键用到了canvas画线的作用融合挪动端touch恶性事件

js一部分是这样的:

window.onload = function() {
    new lineCanvas({
        el: document.getElementById("canvas"),//绘图canvas的父级div
        clearEl: document.getElementById("clearCanvas"),//消除按钮
        saveEl: document.getElementById("saveCanvas"),//储存按钮
        //      linewidth:1,//线条粗细,选填
        //      color:"black",//线条色调,选填
        //      background:"#ffffff"//线条情况,选填
    });
};
function lineCanvas(obj) {
    this.linewidth = 1;
    this.color = "#000000";
    this.background = "#ffffff";
    for (var i in obj) {
        this[i] = obj[i];
    };
    this.canvas = document.createElement("canvas");
    this.el.appendChild(this.canvas);
    this.cxt = this.canvas.getContext("2d");
    this.canvas.width = this.el.clientWidth;
    this.canvas.height = this.el.clientHeight;
    this.cxt.fillStyle = this.background;
    this.cxt.fillRect(0, 0, this.canvas.width, this.canvas.width);
    this.cxt.strokeStyle = this.color;
    this.cxt.lineWidth = this.linewidth;
    this.cxt.lineCap = "round";
    //刚开始绘图
    this.canvas.addEventListener("touchstart", function(e) {
        this.cxt.beginPath();
        this.cxt.moveTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
    }.bind(this), false);
    //绘图中
    this.canvas.addEventListener("touchmove", function(e) {
        this.cxt.lineTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
        this.cxt.stroke();
    }.bind(this), false);
    //完毕绘图
    this.canvas.addEventListener("touchend", function() {
        this.cxt.closePath();
    }.bind(this), false);
    //消除画布
    this.clearEl.addEventListener("click", function() {
        this.cxt.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }.bind(this), false);
    //储存照片,立即转base64
    this.saveEl.addEventListener("click", function() {
        var imgBase64 = this.canvas.toDataURL();
        console.log(imgBase64);
    }.bind(this), false);
};

这是实际效果图:

附上html和css

<div id="canvas">
    <p id="clearCanvas">消除</p>
    <p id="saveCanvas">储存</p>
</div>

html,body{
    width: 100%;
    height: 100%;
}
#canvas{
    width: 100%;
    height: 100%;
    position: relative;
}
#canvas canvas{
    display: block;
}
#clearCanvas{
    width: 50%;
    height: 40px;
    line-height: 40px;
    text-align: center;
    position: absolute;
    bottom: 0;
    left: 0;
    border: 1px solid #DEDEDE;
    z-index: 1;
}
#saveCanvas{
    width: 50%;
    height: 40px;
    line-height: 40px;
    text-align: center;
    position: absolute;
    bottom: 0;
    right: 0;
    border: 1px solid #DEDEDE;
    z-index: 1;
}

以上便是本文的所有內容,期待对大伙儿的学习培训有一定的协助,也期待大伙儿多多适用脚本制作之家。