Sign with canvas
by thepirat000
HTML
<canvas id="canvas" width="500" height="300"></canvas>
CSS
canvas {
position: absolute;
border: 2px solid;
}
JavaScript
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) => { console.log('move'); this.onMouseMove(e); })
$('#canvas').on("mousedown", (e) => { console.log('down'); this.onMouseDown(e); })
$('#canvas').on("mouseup", () => { console.log('up'); this.onMouseUp(); })
$('#canvas').on("mouseout", () => { console.log('out'); this.onMouseOut(); })
$('#canvas').on("mouseenter", (e) => { console.log('enter'); this.onMouseEnter(e); })
$('#canvas').on("touchmove", (e) => { console.log('touchmove'); this.onMouseMove(e); } );
$('#canvas').on("touchstart", (e) => { console.log('touchstart'); this.onMouseEnter(e); this.onMouseDown(e); } );
$('#canvas').on("touchend", (e) => { console.log('touchend'); this.onMouseUp(); this.onMouseOut(); } );
}
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) {
if (e.touches) {
e = e.touches[0]
}
this.prevX = this.currX
this.prevY = this.currY
this.currX = e.clientX - this.canvas.offsetLeft
this.currY = e.clientY - this.canvas.offsetTop
}
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()
...