forked from hackclub/sprig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbitmap-preview.js
40 lines (33 loc) · 1.19 KB
/
bitmap-preview.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
import { bitmapTextToImageData } from "../engine/bitmap.js";
import { global_state } from "../global_state.js";
const PALETTE = global_state.palette;
class BitmapPreview extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
const shadow = this.attachShadow({ mode: "open" });
this.canvas = shadow.appendChild(document.createElement("canvas"));
this.canvas.style.display = "block";
this.canvas.style.width = "100%";
this.canvas.style.imageRendering = "pixelated";
this.attributeChangedCallback();
}
attributeChangedCallback() {
if (!this.canvas) return;
try {
const data = bitmapTextToImageData(this.getAttribute("text") ?? "", PALETTE);
this.canvas.width = data.width;
this.canvas.height = data.height;
this.canvas.getContext("2d").clearRect(0, 0, data.width, data.height);
this.canvas.getContext("2d").putImageData(data, 0, 0);
} catch {
this.canvas.width = 1;
this.canvas.height = 1;
this.canvas.getContext("2d").clearRect(0, 0, 1, 1);
}
this.staleCanvas = false;
}
static get observedAttributes() { return [ "text" ]; }
}
customElements.define("bitmap-preview", BitmapPreview);