-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
98 lines (76 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
90
91
92
93
94
95
96
97
98
import { Line } from "./models/line.js"
import { Position } from "./models/position.js"
const canvas = document.getElementById("canvas")
const clearButton = document.getElementById("clear-btn")
function setup() {
setupCanvasSize()
}
function setupCanvasSize() {
const screenWidth = window.screen.availWidth
const screenHeight = window.screen.availHeight
canvas.width = screenWidth;
canvas.height = screenHeight;
}
setup()
const ctx = canvas.getContext("2d")
let lines = []
function drawLine(ctx, pos1, pos2) {
ctx.beginPath()
ctx.strokeStyle = 'white'
ctx.lineWidth = 5
ctx.moveTo(pos1.x, pos1.y)
ctx.lineTo(pos2.x, pos2.y)
ctx.stroke()
ctx.closePath()
}
function drawPoint(ctx, pos) {
const img = new Image()
const size = 32
img.src = 'images/point.svg'
img.onload = function() {
ctx.drawImage(img, pos.x - size/2, pos.y - size/2, size, size)
}
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
}
function getMousePosition(canvas, e) {
return new Position(e.offsetX - canvas.offsetLeft, e.offsetY - canvas.offsetTop)
}
// MARK: - Canvas listeners
let mouseIsDown = false
canvas.addEventListener("mousedown", (e) => {
const startPos = getMousePosition(canvas, e)
mouseIsDown = true
const line = new Line(startPos.x, startPos.y, startPos.x, startPos.y)
drawPoint(ctx, startPos)
lines.push(line)
})
canvas.addEventListener("mousemove", (e) => {
if (mouseIsDown) {
redrawAll(canvas, e)
}
})
canvas.addEventListener("mouseup", (e) => {
if (mouseIsDown) {
redrawAll(canvas, e)
mouseIsDown = false
}
})
function redrawAll(canvas, e) {
clearCanvas()
const pos = getMousePosition(canvas, e)
lines[lines.length - 1].updateEndPoint(pos.x, pos.y)
for (const l of lines) {
const lStartPosition = l.getStartPos()
const lEndPosition = l.getEndPos()
drawLine(ctx, lStartPosition, lEndPosition)
drawPoint(ctx, lStartPosition)
drawPoint(ctx, lEndPosition)
}
}
// MARK: - Buttons
clearButton.addEventListener("click", (e) => {
clearCanvas()
lines = []
})