Nikola
Nikola

Reputation: 207

Trigger canvas animation on hover

I have canvas/javascript animation. How do I trigger traces on hover of the logo element?

setInterval(function() {
   traces = !traces
}, 5000)

Link https://codepen.io/NGrdanjski/pen/XKkwAY

Upvotes: 0

Views: 1657

Answers (1)

Matthew Kiefer
Matthew Kiefer

Reputation: 209

An event listener on the canvas will do this for you.

https://codepen.io/mrkiefer/pen/wWmEJb

I removed the setInterval that toggles the traces variable, and instead, added:

cvs.addEventListener("mouseover",function(){
           traces = true;
        });

 cvs.addEventListener("mouseout",function(){
            traces = false;
        });

If you want to turn the trades on only when the mouse is over the logo, then you would add the mouse listeners to the logo div instead:

https://codepen.io/mrkiefer/pen/KroGJo

    logo = document.getElementById("logo");


     logo.addEventListener("mouseover",function(){
           traces = true;
        });

 logo.addEventListener("mouseout",function(){
            traces = false;
        });

Here, when you put the mouse over the stackoverflow logo, the star traces are turned on.

Upvotes: 2

Related Questions