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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| class CanvasObjet {
constructor() { //Paramètres du canvas
this.canvas = document.getElementById("canvas");
this.ctx = this.canvas.getContext('2d');
this.ctx.strokeStyle = '#000000';
this.ctx.lineWidth = 3;
this.draw = false;
this.mousePosition = {
x: 0,
y: 0
};
this.lastPosition = this.mousePosition;
this.clearButton = document.getElementById("erase");
this.canvas.width = 290;
this.canvas.height = 150;
this.evenements();
}
//Gestion des événements
evenements() {
var that = this;
// Stop scrolling (touch)
document.body.addEventListener("touchstart", function (e) {
if (e.target == that.canvas) {
e.preventDefault();
}
});
//Souris
this.canvas.addEventListener("mousedown", function (e) {
that.draw = true;
that.lastPosition = that.getMposition(e);
});
this.canvas.addEventListener("mousemove", function (e) {
that.mousePosition = that.getMposition(e);
that.canvasResult()
});
document.addEventListener("mouseup", function (e) {
that.draw = false;
});
// Touchpad
this.canvas.addEventListener("touchstart", function (e) {
that.mousePosition = that.getTposition(e);
var touch = e.touches[0];
var mouseEvent = new MouseEvent("mousedown", {
clientX: touch.clientX,
clientY: touch.clientY
});
that.canvas.dispatchEvent(mouseEvent);
});
this.canvas.addEventListener("touchmove", function (e) {
var touch = e.touches[0];
var mouseEvent = new MouseEvent("mousemove", {
clientX: touch.clientX,
clientY: touch.clientY
});
that.canvas.dispatchEvent(mouseEvent);
});
this.canvas.addEventListener("touchend", function (e) {
var mouseEvent = new MouseEvent("mouseup", {});
that.canvas.dispatchEvent(mouseEvent);
});
//Effacer
this.clearButton.addEventListener("click", function (e) {
that.clearCanvas()
});
}
// Renvoie les coordonnées de la souris
getMposition(mouseEvent) {
if (this.draw) {
var oRect = this.canvas.getBoundingClientRect();
return {
x: mouseEvent.clientX - oRect.left,
y: mouseEvent.clientY - oRect.top
};
}
}
// Renvoie les coordonnées du pad
getTposition(touchEvent) {
var oRect = this.canvas.getBoundingClientRect();
return {
x: touchEvent.touches[0].clientX - oRect.left,
y: touchEvent.touches[0].clientY - oRect.top
};
}
// Dessin du canvas
canvasResult() {
if (this.draw) {
this.ctx.beginPath();
this.ctx.moveTo(this.lastPosition.x, this.lastPosition.y);
this.ctx.lineTo(this.mousePosition.x, this.mousePosition.y);
this.ctx.stroke();
this.lastPosition = this.mousePosition;
}
};
// Vide le dessin du canvas
clearCanvas() {
this.canvas.width = this.canvas.width;
this.ctx.lineWidth = 3;
}
}
var obj = new CanvasObjet(); |
Partager