-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
67 lines (59 loc) · 1.62 KB
/
main.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
const createCanvas = (width, height) => {
const scale = window.devicePixelRatio;
const canvas = document.createElement("canvas");
canvas.width = width * scale;
canvas.height = height * scale;
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
return canvas;
};
class TenPrint {
constructor({ rootEl, width, height }) {
this.rootEl = rootEl;
this.size = 0;
this.canvas = createCanvas(width, height);
this.ctx = this.canvas.getContext("2d");
this.colors = { primary: "#0282c7", secondary: "#fff" };
}
line(x, y, dx, dy) {
this.ctx.beginPath();
this.ctx.lineWidth = 5;
this.ctx.strokeStyle = this.colors.secondary;
this.ctx.moveTo(x, y);
this.ctx.lineTo(dx, dy);
this.ctx.stroke();
}
draw() {
this.ctx.fillStyle = this.colors.primary;
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
for (let y = 0; y <= this.canvas.height; y += this.size) {
for (let x = 0; x < this.canvas.width; x += this.size) {
if (Math.random() > 0.5) {
this.line(x, y, x + this.size, y + this.size);
} else {
this.line(x + this.size, y, x, y + this.size);
}
}
}
}
init({ size }) {
this.size = size;
this.rootEl.appendChild(this.canvas);
this.draw();
}
}
const container = document.querySelector(".container");
const sizeInput = document.querySelector(".size-input");
const tenPrint = new TenPrint({
width: 400,
height: 400,
rootEl: container,
});
const initializeTenPrint = () => {
const size = parseInt(sizeInput.value, 10);
if (!isNaN(size)) {
tenPrint.init({ size });
}
};
initializeTenPrint();
sizeInput.addEventListener("input", initializeTenPrint);