-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
95 lines (79 loc) · 2.37 KB
/
app.js
File metadata and controls
95 lines (79 loc) · 2.37 KB
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
const canvas = document.getElementById("jsCanvas");
const ctx = canvas.getContext("2d");
const colors = document.getElementsByClassName("jsColor");
const rangeControl = document.querySelector('.range');
const mode = document.querySelector('#jsMode');
const saveBtn = document.querySelector('#jsSave');
const CANVAS_WIDTH = window.innerWidth*0.8;
const CANVAS_HEIGHT = window.innerHeight*0.8;
const INITIAL_COLOR = "#1e1a1a";
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
ctx.fillStyle = "#fff";
ctx.fillRect(0,0,CANVAS_WIDTH, CANVAS_HEIGHT);
ctx.strokeStyle = INITIAL_COLOR;
ctx.lineWidth = 2.5;
let painting = false;
let filling = false;
function stopPainting(event){
painting = false;
}
function startPainting(event){
painting = true;
}
function onMouseMove(event){
const x = event.offsetX;
const y = event.offsetY;
if(!painting){
ctx.beginPath();
ctx.moveTo(x,y);
}else {
ctx.lineTo(x,y);
ctx.stroke();
}
}
function handleColorClick(event) {
const color = event.target.style.backgroundColor;
ctx.strokeStyle = color;
ctx.fillStyle = color;
}
function handleRangeControl(event){
const thickness = event.target.value;
ctx.lineWidth = thickness;
}
function handleModeCLick(){
if(filling === true){
filling = false;
mode.innerText = "Fill";
}else{
filling = true;
mode.innerText = "Paint";
}
}
function handleCanvasClick(){
if(filling === true){
ctx.fillRect(0,0, CANVAS_WIDTH,CANVAS_HEIGHT);
}
}
function handleCM(event){
event.preventDefault();
}
function handleSaveBtnClick(){
const image = canvas.toDataURL("image/jpeg");
const link = document.createElement("a");
link.href = image;
link.download = "PaintJS";
link.click();
}
if(canvas){
canvas.addEventListener("mousemove", onMouseMove);
canvas.addEventListener("mousedown", startPainting);
canvas.addEventListener("mouseup", stopPainting);
canvas.addEventListener("mouseleave", stopPainting);
canvas.addEventListener("click", handleCanvasClick );
canvas.addEventListener("contextmenu", handleCM);
}
Array.from(colors).forEach(color => color.addEventListener("click", handleColorClick));
rangeControl.addEventListener("input", handleRangeControl);
mode.addEventListener("click", handleModeCLick);
saveBtn.addEventListener("click", handleSaveBtnClick);