-
Notifications
You must be signed in to change notification settings - Fork 0
/
canvas.js
59 lines (56 loc) · 1.44 KB
/
canvas.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
import S from "https://cdn.skypack.dev/s-js";
function resolve(value) {
if (typeof value === "function") {
return resolve(value());
} else {
return value;
}
}
function draw(context, data) {
if (Array.isArray(data)) {
for (let item of data) {
draw(context, item);
}
} else {
const { translate, scale, path, children, ...props } = data;
context.save();
context.beginPath();
for (let [key, value] of Object.entries(props)) {
context[key] = resolve(value);
}
if (resolve(translate)) {
context.translate(...resolve(translate));
}
if (resolve(scale)) {
context.scale(...resolve(scale));
}
if (path) {
for (let { op, args } of path) {
context[op](...args);
}
}
context.closePath();
context.fill();
context.stroke();
context.restore();
}
}
export function canvas(data) {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
const observer = new ResizeObserver((entries) => {
for (let entry of entries) {
console.log(entry.contentBoxSize.inlineSize);
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
context.clearRect(0, 0, entry.target.width, entry.target.height);
draw(context, data);
}
});
observer.observe(canvas);
S(() => {
context.clearRect(0, 0, canvas.width, canvas.height);
draw(context, data);
});
return canvas;
}