-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (79 loc) · 2.14 KB
/
index.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
//window.addEventListener("load", () => {
//
//});
/*window.addEventListener('resize', winSize);
function winSize() {
canvas.height=window.innerHeight;
canvas.width=window.innerWidth;
}
*/
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
//ctx.strokeStyle = "#f00";
//ctx.fillStyle = "#fff";
//ctx.fillRect=(0,0, canvas.width, canvas.height);
let prevX, prevY, currX, currY;
let paint = false;
function startPosition() {
paint = true;
}
function finishPosition() {
paint = false;
ctx.beginPath();
}
canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mouseup", finishPosition);
canvas.addEventListener("mousemove", (e) => {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
draw();
});
function _(e, all = false) {
let divs = document.querySelectorAll(e);
if (all || (divs.length > 1)) {
return divs;
}
return divs[0];
}
_('[name="color"]').addEventListener('change', function(e) {
ctx.strokeStyle = e.target.value;
ctx.fillStyle = e.target.value;
});
_('[name="width"]').addEventListener('change', function(e) {
if (e.target.value < 1) {
return false;
}
if (e.target.value > 10) {
return false;
}
lineWidth = Math.round(e.target.value);
ctx.lineWidth = lineWidth;
});
function draw(e) {
if (!paint) return;
ctx.lineCap = "round";
ctx.beginPath();
//ctx.moveTo(e.clientX, e.clientY);
//ctx.lineTo(e.clientX, e.clientY);
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
ctx.stroke();
//ctx.closePath();
}
function clearCanvas() {
let lastFllStyle = ctx.fillStyle
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, 5000, 5000);
ctx.fillStyle = lastFllStyle;
confirm("Do you want to reset?");
};
function download() {
let link = document.createElement('a');
link.setAttribute('download', 'draw.png');
link.setAttribute('href', canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"));
link.click();
};