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
}());