1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
"use strict";
class Signature {
constructor() {
this.color = "#000000";
this.sign = false;
this.begin_sign = false;
this.width_line = 5;
this.canvas = document.getElementById('canvas');
this.offsetLeft = this.canvas.offsetLeft;
this.offsetTop = this.canvas.offsetTop;
this.context = canvas.getContext('2d');
this.context.lineJoin = 'round';
this.context.lineCap = 'round';
this.whenActionDown();
this.whenActionUp();
this.whenActionMove();
this.createSignature();
this.clearCanvas();
this.resetCanvas();
}
updateMousePosition(mX, mY) {
let rect = this.canvas.getBoundingClientRect();
let scaleX = this.canvas.width / rect.width;
let scaleY = this.canvas.height / rect.height;
this.cursorX = (mX - rect.left) * scaleX;
this.cursorY = (mY - rect.top) * scaleY;
}
updateFingerPosition(canvas, evt) {
let mobilerect = this.canvas.getBoundingClientRect();
const e = evt.touches ? evt.touches[0] : evt;
return {
x: Math.round(e.clientX - mobilerect.left),
y: Math.round(e.clientY - mobilerect.top)
};
evt.preventDefault();
}
actionDown(e) {
this.sign = true;
this.updateMousePosition(e.clientX, e.clientY);
this.updateFingerPosition(e.clientX, e.clientY);
}
actionUp() {
this.sign = false;
this.begin_sign = false;
}
actionMove(e) {
if (this.sign) {
this.updateMousePosition(e.clientX, e.clientY);
this.updateFingerPosition(e.clientX, e.clientY);
this.createSignature();
}
}
whenActionDown() {
document.addEventListener("mousedown", this.actionDown.bind(this));
document.addEventListener("touchstart", this.actionDown.bind(this));
}
whenActionUp() {
document.addEventListener("mouseup", this.actionUp.bind(this));
document.addEventListener("touchend", this.actionUp.bind(this));
}
whenActionMove() {
this.canvas.addEventListener('mousemove', this.actionMove.bind(this));
this.canvas.addEventListener('touchmove', this.actionMove.bind(this));
}
createSignature() {
if (!this.begin_sign) {
this.context.beginPath();
this.context.moveTo(this.cursorX, this.cursorY);
this.begin_sign = true;
} else {
this.context.lineTo(this.cursorX, this.cursorY);
this.context.strokeStyle = this.color;
this.context.lineWidth = this.width_line;
this.context.stroke();
}
}
clearCanvas() {
this.context.clearRect(0, 0, this.canvas.offsetWidth, this.canvas.offsetHeight);
}
resetCanvas() {
document.getElementById("reset").addEventListener("click", () => {
this.clearCanvas();
})
}
}
document.addEventListener("DOMContentLoaded", event => {
new Signature();
}); |
Partager