Created
May 30, 2019 08:47
-
-
Save alexwebgr/553936bcb948d6f0d24ef8fbfd8bf347 to your computer and use it in GitHub Desktop.
Digital signature field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SignTool { | |
constructor() { | |
this.initVars(); | |
this.initEvents(); | |
} | |
initVars() { | |
this.canvas = $('#canvas')[0]; | |
this.ctx = this.canvas.getContext("2d"); | |
this.isMouseClicked = false; | |
this.isMouseInCanvas = false; | |
this.prevX = 0; | |
this.currX = 0; | |
this.prevY = 0; | |
this.currY = 0; | |
} | |
initEvents() { | |
$('#canvas').on("mousemove", (e) => this.onMouseMove(e)); | |
$('#canvas').on("mousedown", (e) => this.onMouseDown(e)); | |
$('#canvas').on("mouseup", () => this.onMouseUp()); | |
$('#canvas').on("mouseout", () => this.onMouseOut()); | |
$('#canvas').on("mouseenter", (e) => this.onMouseEnter(e)); | |
} | |
onMouseDown(e) { | |
this.isMouseClicked = true; | |
this.updateCurrentPosition(e); | |
} | |
onMouseUp() { | |
this.isMouseClicked = false; | |
} | |
onMouseEnter(e) { | |
this.isMouseInCanvas = true; | |
this.updateCurrentPosition(e); | |
} | |
onMouseOut() { | |
this.isMouseInCanvas = false; | |
} | |
onMouseMove(e) { | |
if (this.isMouseClicked && this.isMouseInCanvas) { | |
this.updateCurrentPosition(e); | |
this.draw(); | |
} | |
} | |
updateCurrentPosition(e) { | |
this.prevX = this.currX; | |
this.prevY = this.currY; | |
this.currX = e.offsetX ; | |
this.currY = e.offsetY; | |
} | |
draw() { | |
this.ctx.beginPath(); | |
this.ctx.moveTo(this.prevX, this.prevY); | |
this.ctx.lineTo(this.currX, this.currY); | |
this.ctx.strokeStyle = "black"; | |
this.ctx.lineWidth = 2; | |
this.ctx.stroke(); | |
this.ctx.closePath(); | |
} | |
save() { | |
return this.canvas.toDataURL(); | |
} | |
erase() { | |
var ctx = this.canvas.getContext("2d"); | |
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); | |
} | |
} | |
var canvas = new SignTool(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment