UNPKG

dic-writing-pad

Version:

兼容手写笔的手写板

78 lines (76 loc) 3.18 kB
class dicWritingPad { constructor(options = {}) { this.colours = options.colours || '#000' // 手写笔颜色 默认为黑色 this.lineWidth = options.lineWidth || 10 //笔记宽度 默认为10 this.onDrading = options.onDrading || null if(options.customId){ this.customId = options.customId }else{ throw new Error('未指定渲染customId') } this.DrawFigure(document.getElementById(options.customId)) } DrawFigure(canvas) { let _this = this; this.canvas = canvas; console.log("+++",this.canvas.parentNode) this.canvas.width = this.canvas.parentNode.clientWidth; this.canvas.height = this.canvas.parentNode.clientHeight; this._ctx = this.canvas.getContext('2d'); this.lastPt = {}; this._handleMouseDown = function(event) { _this._mouseButtonDown = true; // console.log("按下去") } this._handleMouseMove = function(event) { var id = event.pointerId; if(_this._mouseButtonDown) { // console.log("移动中",event) var event = window.event || event; if(_this.onDrading !== null){ _this.onDrading() } if(_this.lastPt[id]) { _this._ctx.beginPath(); _this._ctx.moveTo(_this.lastPt[id].x,_this.lastPt[id].y); _this._ctx.lineTo(event.offsetX,event.offsetY); _this._ctx.lineCap="round"; _this._ctx.strokeStyle = _this.colours; _this._ctx.lineWidth = _this.lineWidth; _this._ctx.stroke(); } _this.lastPt[id] = { x: event.offsetX, y: event.offsetY } } event.preventDefault() } this._handleMouseUp = function(event) { // console.log("松起") var id = event.pointerId; _this._mouseButtonDown = false; _this.canvas.removeEventListener('pointermove',_this.__handleMouseMove,false); _this.canvas.removeEventListener('mousemove',_this.__handleMouseMove,false); delete _this.lastPt[id]; } this.Init() } Init() { this._mouseButtonDown = false; if(window.PointerEvent) { this.canvas.addEventListener('pointerdown',this._handleMouseDown,false); this.canvas.addEventListener('pointermove',this._handleMouseMove,false); this.canvas.addEventListener('pointerup',this._handleMouseUp,false); } else { this.canvas.addEventListener('mousedownn',this._handleMouseDown,false); this.canvas.addEventListener('mousemove',this._handleMouseMove,false); this.canvas.addEventListener('mouseup',this._handleMouseUp,false); } } ToBase64(){ let base64 = this.canvas.toDataURL("image/png") return base64 } } export default dicWritingPad