-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfire.js
More file actions
105 lines (89 loc) · 2.46 KB
/
fire.js
File metadata and controls
105 lines (89 loc) · 2.46 KB
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
99
100
101
102
103
104
105
(() => {
const fireColorsPalette = [
"rgb(7,7,7)",
"rgb(31,7,7)",
"rgb(47,15,7)",
"rgb(71,15,7)",
"rgb(87,23,7)",
"rgb(103,31,7)",
"rgb(119,31,7)",
"rgb(143,39,7)",
"rgb(159,47,7)",
"rgb(175,63,7)",
"rgb(191,71,7)",
"rgb(199,71,7)",
"rgb(223,79,7)",
"rgb(223,87,7)",
"rgb(223,87,7)",
"rgb(215,95,7)",
"rgb(215,95,7)",
"rgb(215,103,15)",
"rgb(207,111,15)",
"rgb(207,119,15)",
"rgb(207,127,15)",
"rgb(207,135,23)",
"rgb(199,135,23)",
"rgb(199,143,23)",
"rgb(199,151,31)",
"rgb(191,159,31)",
"rgb(191,159,31)",
"rgb(191,167,39)",
"rgb(191,167,39)",
"rgb(191,175,47)",
"rgb(183,175,47)",
"rgb(183,183,47)",
"rgb(183,183,55)",
"rgb(207,207,111)",
"rgb(223,223,159)",
"rgb(239,239,199)",
"rgb(255,255,255)"
];
const pixelSize = 20;
const prepareCanvas = canvasQuery => {
const canvas = document.querySelector(canvasQuery);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
return canvas;
};
const createFireDataStructure = ({ x, y }) =>
Array.from({ length: x * y }, () => 0);
const getFireResolution = canvas => ({
x: Math.ceil(canvas.width / pixelSize),
y: Math.ceil(canvas.height / pixelSize)
});
const setFireSource = (fire, size, level = 36) => {
for (let x = fire.length - size.x; x < fire.length; x++) {
fire[x] = level;
}
};
const calculateFirePropagation = (fire, size) => {
for (let y = 0; y < size.y - 1; y++) {
for (let x = 0; x < size.x; x++) {
const decay = Math.floor(Math.random() * 3);
const pixelIndex = y * size.x + x;
fire[pixelIndex - decay] = fire[pixelIndex + size.x] - decay;
}
}
};
const renderFire = (fire, size, ctx) => {
for (let y = 0; y < size.y; y++) {
for (let x = 0; x < size.x; x++) {
const pixel = fire[y * size.x + x];
ctx.fillStyle = fireColorsPalette[pixel] || fireColorsPalette[0];
ctx.fillRect(x * pixelSize, y * pixelSize, pixelSize, pixelSize);
}
}
};
const setFire = () => {
const canvas = prepareCanvas(".doomFireCanvas");
const context = canvas.getContext("2d");
const size = getFireResolution(canvas);
let fire = createFireDataStructure(size);
setFireSource(fire, size);
setInterval(() => {
calculateFirePropagation(fire, size);
renderFire(fire, size, context);
}, 50);
};
setFire();
})();