欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

html5 利用canvas手写签名并保存的实现方法

程序员文章站 2023-12-14 13:27:52
这篇文章主要介绍了html5 利用canvas手写签名并保存的实现方法的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧... 18-07-12...

最近公司在做一个签名的功能,主要用到了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);
};

这是效果图:

html5 利用canvas手写签名并保存的实现方法

附上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;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: