Skip to content
Advertisement

Stencil js – requestAnimationFrame does not occure in all components

I created a simple catalog item component using stencil.js. In the component there is canvas tag that on it I painted animating curved lines. At the componentDidLoad function, I define the canvas, initialize it and call the animate function. This is the code of the component itself:

JavaScript

As you can see, I import the canvas code, here it is:

JavaScript

Now, the catalog item component is inside of a container component like so:

JavaScript

The end result is that the components are showing the canvas and the lines however animation ocurres only in one of them. The rest are static in theire initial state. Please tell me why it happens and what i can do to fix it so that all of the components will animate. It is important to note that when i refresh the code and the browser refreshes via hot reload, another component starts animate and so on with each refresh.

Thank you for your help.

Advertisement

Answer

The problem is that some variables are defined outside the initCanvas function and therefore shared between all the components (line1, line2, ctx and canvasElem). So each time you call initCanvas they are overwritten.

A quick solution would be to wrap it in a class:

JavaScript

And then instantiate it in the component:

JavaScript

This way each instance of WaveCanvas will hold its own reference to the correct <canvas> element.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement