forked from devoffarg/DevOff-Desafio-3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
96 lines (85 loc) · 2.26 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
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
let colorSelected = "black"
let lineSelected = 2
const draw = () => {
let isDrawing = false;
let x = 0;
let y = 0;
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
canvas.addEventListener('mousedown', e => {
e.preventDefault()
x = e.offsetX;
y = e.offsetY;
isDrawing = true;
});
canvas.addEventListener('mousemove', e => {
e.preventDefault()
if (isDrawing === true) {
drawLine(context, x, y, e.offsetX, e.offsetY);
x = e.offsetX;
y = e.offsetY;
}
});
window.addEventListener('mouseup', e => {
e.preventDefault()
if (isDrawing === true) {
drawLine(context, x, y, e.offsetX, e.offsetY);
x = 0;
y = 0;
isDrawing = false;
}
});
function drawLine(context, x1, y1, x2, y2) {
context.beginPath();
context.strokeStyle = colorSelected
if (colorSelected === "multicolor") {
context.strokeStyle = "#" + Math.floor(Math.random()*16777215).toString(16);
}
context.strokeStyle = colorSelected
context.lineWidth = lineSelected;
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.stroke();
context.closePath();
}
}
const chooseColor = colorName => {
if (colorName !== colorSelected) {
document.getElementById(colorName).style.border = "5px solid darkgrey"
document.getElementById(colorSelected).style.border = "none"
}
colorSelected = colorName
}
const getLineElement = value => {
let element
switch(value) {
case 2:
element = document.getElementById("very-small")
break
case 4:
element = document.getElementById("small")
break
case 6:
element = document.getElementById("medium")
break
case 8:
element = document.getElementById("big-medium")
break
case 10:
element = document.getElementById("big")
break
}
return element
}
const chooseLine = lineSize => {
if (lineSize !== lineSelected) {
getLineElement(lineSize).style.backgroundColor = "darkgrey"
getLineElement(lineSelected).style.backgroundColor = "black"
}
lineSelected = lineSize
}
const saveDrawing = () => {
const canvas = document.getElementById('canvas');
const image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); // here is the most important part because if you dont replace you will get a DOM 18 exception.
window.location.href=image;
}