VincentGarreau / particles.js

A lightweight JavaScript library for creating particles
https://vincentgarreau.com/particles.js/
MIT License
28.98k stars 4.82k forks source link

Handle mouse events on forward element #102

Open ArthurGerbelot opened 8 years ago

ArthurGerbelot commented 8 years ago

Hi,

I have updated my particules.js fine to dispatch the mousemove event from forward html elements to particles canvas. You can easly integrate it (I tried but i'm not autorized) on particules.js by adding:

line 102 dispatched_events_selector: null,

line 1161

    if(pJS.interactivity.dispatched_events_selector){
      let dispatch = function(event) {
        let new_event = document.createEvent('MouseEvents')
        new_event.initMouseEvent(event.type,true,true,document.defaultView, 0,
          event.screenX, event.screenY, event.clientX, event.clientY,
          false,false,false,false,null,null)
        pJS.interactivity.el.dispatchEvent(new_event)
      }
      let loopElements = function(els) {
        let length = els.length
        for (let el_idx=0; el_idx<length; el_idx++) {
          els[el_idx].addEventListener('mousemove', dispatch)
          els[el_idx].addEventListener('click', dispatch)
        }
      }
      if (pJS.interactivity.dispatched_events_selector) {
        loopElements(document.querySelectorAll(pJS.interactivity.dispatched_events_selector))
      }
    }

This update will add pJS.interactivity.dispatched_events_selector configuration (can be #id, .class or tag. As CSS, can by multiple), trigger the mousemove and click event, and dispatch to particules canvas.

Fianl code available on my forked branch: https://github.com/ArthurGerbelot/particles.js


You can test it (only mousemove event) by adding this code browser console on the Git Example:

document.getElementsByClassName('panel')[0].addEventListener('mousemove', function(e) { 
    var e = document.createEvent('MouseEvents');
    e.initMouseEvent('mousemove',true,true,document.defaultView, 0, event.screenX, event.screenY, event.clientX, event.clientY,false,false,false,false,null,null);
    document.getElementById("particles-js").childNodes[0].dispatchEvent(e) 
})
edulelis commented 8 years ago

A similar effect can also be achieved with css using pointer-events: none on the foreground element.

ArthurGerbelot commented 8 years ago

@edulelis nice catch, but pointer-event have a bad compatibility: http://caniuse.com/#feat=pointer-events