粒子在mousemove上跟随光标(Javascript-Canvas) [英] Particles follow cursor on mousemove (Javascript - Canvas)

查看:54
本文介绍了粒子在mousemove上跟随光标(Javascript-Canvas)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的动画,其中某些粒子动画会跟随光标,但是我遇到了麻烦.

我创建了一个小提琴来复制该问题:关于JSFiddle的示例

现在我的粒子出现了,但是当您将光标移到该部分上时,它们突然消失了.我知道我的错误来自我的 mousemove()函数,但是我无法弄清楚它出了什么问题.

这是我的mousemove函数:

 功能mouseMove(e){var posx = posy = 0;如果(e.pageX || e.pageY){posx = e.pageX;posy = e.pageY;}否则,如果(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 =诗意;} 

解决方案

您的鼠标坐标X,Y相对于网页的左上角,可能mousemove事件是附加到文档而不是画布上的.将mosemove事件附加到画布上

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

并使用基本的偏移量:

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

如果您希望鼠标位于图形的中心,请使用e.offsetY-something,其中某些东西是图形高度的一半

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

这篇关于粒子在mousemove上跟随光标(Javascript-Canvas)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆