-
Notifications
You must be signed in to change notification settings - Fork 704
/
Copy pathscaler.js
45 lines (39 loc) · 1.29 KB
/
scaler.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
export class Scaler extends HTMLElement {
static observedAttributes = ["canvaswidth", "canvasheight"];
#shadowRoot;
#scaledElement;
#contentElement;
attributeChangedCallback(name, oldValue, newValue) {
const width = Number(this.getAttribute("canvaswidth"));
const height = Number(this.getAttribute("canvasheight"));
this.#contentElement.style.aspectRatio = `${width} / ${height}`;
this.#scaledElement.style.width = `${width}px`;
this.#scaledElement.style.height = `${height}px`;
}
constructor() {
super();
this.#shadowRoot = this.attachShadow({ mode: "closed" });
this.#shadowRoot.innerHTML = `
<style>
.content {
contain: strict;
overflow: hidden;
}
.scaled {
transform-origin: 0 0;
}
</style>
<div class="content">
<div class="scaled"><slot></slot></div>
</div>
`;
this.#scaledElement = this.#shadowRoot.querySelector(".scaled");
this.#contentElement = this.#shadowRoot.querySelector(".content");
new ResizeObserver(([entry]) => {
this.#scaledElement.style.transform = `scale(${
entry.contentRect.width / Number(this.getAttribute("canvaswidth"))
})`;
}).observe(this.#contentElement);
}
}
customElements.define("spec-scaler", Scaler);