Reputation: 7909
I am developing a web component that renders some graphics on a <canvas>
, that appended to the component's shadowRoot
I would like to re-size and re-render the canvas when the size of the element changes (e.g. its CSS width
property is updated).
How to do so? Should I be using a ResizeObserver
?
Upvotes: 1
Views: 1047
Reputation: 192
I agree with the answer @Steren provided, but will add one more detail which might help others like me.
The component might default to a style display: inline
and cause the resizeObserver
not to work. So by setting it to dispaly: block
the observer will be fired when the component resizes.
constructor() {
super();
const resizeObserver = new ResizeObserver(() => {
// re-render my canvas
});
resizeObserver.observe(this);
this.style.display = "block"
}
Upvotes: 0
Reputation: 7909
I ended up using a ResizeObserver
in the constructor of my custom element:
constructor() {
super();
const resizeObserver = new ResizeObserver(() => {
// re-render my canvas
});
resizeObserver.observe(this);
}
Upvotes: 2