-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2d.js
47 lines (41 loc) · 1.42 KB
/
2d.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
import Maze from "./maze.js";
const ctx = document.querySelector('canvas').getContext('2d');
const inputs = document.querySelectorAll('input');
const scale = 10;
document.addEventListener('keydown', e => {
if (e.key === 'Enter') drawMaze();
})
document.querySelector('#print').addEventListener('click', () => window.print());
document.querySelector('#generate').addEventListener('click', drawMaze);
function drawMaze() {
document.querySelector('#print').hidden = false;
let [height, width, thickness] = [...inputs].map(a => +a.value);
height = Math.floor(height);
width = Math.floor(width);
if (!(height > 0 && width > 0 && 0 < thickness && thickness < 1)) {
alert('Please enter valid values');
return;
}
ctx.canvas.height = (height + 1) * scale;
ctx.canvas.width = (width + 1) * scale;
ctx.setTransform(scale, 0, 0, scale, 10.5, 10.5);
ctx.fillRect(-1, -1, width + 1, height + 1);
const { lines, segments } = new Maze(width, height);
ctx.lineWidth = thickness;
ctx.strokeStyle = '#ffffff';
ctx.beginPath();
ctx.moveTo(0, -1);
for (const { start, end } of lines) {
ctx.lineTo(...start);
ctx.lineTo(...end);
}
ctx.lineTo(width - 1, height);
ctx.stroke();
ctx.lineCap = 'square';
for (const { start, end } of segments) {
ctx.beginPath();
ctx.moveTo(...start);
ctx.lineTo(...end);
ctx.stroke();
}
}