简体   繁体   中英

Particles follow cursor on mousemove (Javascript - Canvas)

I'm trying to create a simple animation where some particles animation follow the cursor, but i'm having trouble with it.

I've created a fiddle to replicate the issue : Example on JSFiddle

Right now my particles appear, but when you move the cursor over the section, they suddenly disappear. I know my error comes from my mousemove() function, but i can't figure out what is wrong with it..

here is my mousemove function :

function mouseMove(e) {
        var posx = posy = 0;
        if (e.pageX || e.pageY) {
            posx = e.pageX;
            posy = e.pageY;
        }
        else if (e.clientX || e.clientY)    {
            posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }
        target.x = posx;
        target.y = posy;
    }

Your mouse coordinate X, Y is relative to the top/left corner of the web page, probably mousemove event is attached to document, not to the canvas. Attach the mosemove event to the canvas

document.getElementById('services-canvas').addEventListener('mousemove', mouseMove);

And use the elemnt ofset:

target.x = e.offsetX;
target.y = e.offsetY;

If you would like the mouse to be in the centre of figure, then use e.offsetY-something where something is half of height of figure

So your particles do actually follow the mouse from what I have seen in . However, it seems that they are way lower in the y position that you would expect.You need to do this to make it work properly:

target.y = posy -300;

I have tried it and it worked with this little change. Hope this helped :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM