-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
67 lines (52 loc) · 1.79 KB
/
script.js
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
const canvas = document.querySelector("canvas");
const toolButtons = document.querySelectorAll(".tool");
const ctx = canvas.getContext("2d");
let prevMouseX, prevMouseY, snapshot;
let isDrawing = false;
let selectedTool = "brush";
let burshWidth = 5;
window.addEventListener("load", () => {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
});
const drawRectangle = (e) => {
ctx.strokeRect(e.offsetX, e.offsetY, prevMouseX - e.offsetX, prevMouseY - e.offsetY);
}
const startDraw = (e) => {
isDrawing = true;
prevMouseX = e.offsetX;
prevMouseY = e.offsetY;
ctx.beginPath();
ctx.lineWidth = burshWidth;
snapshot = ctx.getImageData(0, 0, canvas.width, canvas.height)
}
const stopDraw = () => {
isDrawing = false;
}
const drawing = (e) => {
if(!isDrawing) return;
ctx.putImageData(snapshot, 0, 0);
if(selectedTool === "brush"){
ctx.lineTo(e.offsetX, e.offsetY); // creating line according to the mouse
ctx.stroke(); // drawing/filling line with colour
}else if(selectedTool === "rectangle"){
drawRectangle(e);
}
}
toolButtons.forEach(button => {
button.addEventListener("click", () => {
document.querySelector(".options .active").classList.remove("active");
button.classList.add("active");
selectedTool = button.id;
console.log(button.id);
})
})
//const clearCanvasButton = document.getElementsByClassName("clear-canvas");
//clearCanvasButton.addEventListener("click", pressClearCanvas);
/*function pressClearCanvas(){
//const contex = canvas.getContext("2d");
contex.clearRect(0, 0, canvas.width, canvas.height);
}*/
canvas.addEventListener("mousedown", startDraw);
canvas.addEventListener("mouseup", stopDraw);
canvas.addEventListener("mousemove", drawing);