js基于canvas实现签字
近期项目开发需要用户签字审核,所以就研究了下,为了方便以后使用就封装成了插件,兼容性一般,因为我们公司只考虑Chrome。
调用方法:
var signature = new Signature('#canvas')//画笔默认样式宽度为2,颜色#000000
var signature = new Signature('#canvas',{width:1,color:'red'})//初始化时可以设置样式
//需要动态改变画笔样式可以调用setStyle()方法
signature.setStyle({color:'#264587',width:4})
//清空画板
signature.clear()
//画板内容转成图片(base64)
console.log(signature.toBase64())
//监听画板内容变化
signature.change(function(e){
console.log(e)//回调参数为toBase64()的返回值
})
插件源码,实现原理很简单,欢迎指出不足之处
var Signature = (function() {
"use strict"
function Signature(selector,options) {
this.options = options || {}
this.canvas = document.querySelector(selector)
if(!this.canvas){
console.error(selector+": This element is undefined.")
return
}
this.canvasWidth = this.canvas.width
this.canvasHeight = this.canvas.height
this.isSupportTouch = 'ontouchstart' in window
this.events = 'ontouchstart' in window ? ['touchstart', 'touchmove', 'touchend'] : ['mousedown', 'mousemove', 'mouseup']
this.ctx = this.canvas.getContext('2d');
this.changeFun = null
this.init(this)
}
Signature.prototype = {
constructor: Signature,
init: function(that){
that.canvas.addEventListener(that.events[0], function() {that.startEventHandler(window.event)}, false)
},
startEventHandler: function(event) {
event.preventDefault();
this.ctx.beginPath();
this.ctx.lineWidth = this.options.width || 2;
this.ctx.strokeStyle = this.options.color || '#000000';
(this.moveEventHandler = this.moveEventHandler.bind(this)), (this.endEventHandler = this.endEventHandler.bind(this));
window.addEventListener(this.events[1], this.moveEventHandler, false);
window.addEventListener(this.events[2], this.endEventHandler, false);
},
moveEventHandler: function(event) {
event.preventDefault();
this.evt = this.isSupportTouch ? event.touches[0] : event;
this.coverPos = this.canvas.getBoundingClientRect();
this.mouseX = this.evt.clientX - this.coverPos.left;
this.mouseY = this.evt.clientY - this.coverPos.top;
this.ctx.lineTo(this.mouseX, this.mouseY);
this.ctx.stroke();
},
endEventHandler: function(event) {
event.preventDefault();
window.removeEventListener(this.events[1], this.moveEventHandler, false);
window.removeEventListener(this.events[2], this.endEventHandler, false);
this.change(this.changeFun)
},
change: function(fun){
if(!this.changeFun){
this.changeFun = fun
return
}
this.changeFun(this.toBase64())
},
setStyle: function(obj){
Object.assign(this.options,obj)
},
clear: function() {
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
this.ctx.closePath();
},
toBase64: function(type) {
type = type ? type : 'png'
switch (type) {
case 'png':
this.dataurl = this.canvas.toDataURL('image/png');
break;
case 'jpg':
this.dataurl = this.canvas.toDataURL('image/jpeg', 0.8);
break;
}
return this.dataurl
}
}
return Signature
}());