Using stencil.js, I have developed a unique catalog item component featuring an animating curved lines painted on a canvas tag within the component. In the componentDidLoad function, the canvas is defined, initialized, and the animate function is called. Here's the code snippet of the component:
import { Component, Host, h, Prop, Element } from "@stencil/core";
import { Item } from "../hotb-catalog-container/data";
import { initCanvas, init, animate } from "./wave.js";
import axios from "axios";
@Component({
tag: "hotb-catalog-item",
styleUrl: "hotb-catalog-item.scss",
shadow: false,
})
export class HotbCatalogItem {
@Prop() item: Item;
@Element() el: HTMLElement;
// @Event({ bubbles: true, composed: true }) itemSelect: EventEmitter<Item>;
itemSelected(event: Event) {
event.preventDefault();
//sessionStorage.setItem("item", JSON.stringify(this.item));
axios.post("/item", { item: this.item }).then(() => {
window.location.href = "http://localhost:3000/item";
});
}
componentDidLoad() {
let canvas = this.el.querySelector('canvas');
initCanvas(canvas);
init();
animate();
}
render() {
return (
<Host>
<div class="heading">
<h1>{this.item.name}</h1>
<span> מ{this.item.origin} · {this.item.taste}</span>
</div>
<div class="center-part">
<div class="center-part__img"></div>
<div class="center-part__icon center-part__icon--temp">
{this.item.temp}°C
</div>
<div class="center-part__icon center-part__icon--time">
{this.item.time}
</div>
</div>
<a
href="/item"
onClick={this.itemSelected.bind(this)}
class="primary-btn homepage__tea"
>
לצפיה
</a>
<canvas></canvas>
</Host>
);
}
}
The imported canvas code looks like this:
let line1;
let line2;
var ctx;
var canvasElem;
function initCanvas(canvas) {
canvasElem = canvas;
ctx = canvas.getContext("2d");
const parent = canvas.parentElement;
canvas.width = parent.clientWidth;
canvas.height = parent.scrollHeight;
}
class LineGen {
...
The catalog item component is nested inside a container component as shown below:
let items;
if (this.newItemsArr.length == 0) {
items = <div class="no-items">אין משקאות שתואמים לחיפוש שלך</div>;
} else {
items = this.newItemsArr.map((item) => (
<hotb-catalog-item item={item}></hotb-catalog-item>
));
}
return (
<Host>
{items}
</Host>
);
However, only one of the components animates while the others remain static in their initial state. Refreshing the code triggers animation in another component with each refresh cycle. Please advise me on how to resolve this issue and ensure that all components animate properly.
Thank you for your assistance.