Chapter 15: Solution for Mouse trail exercise (hint) · Issue #541 · marijnh/Eloquent-JavaScript · GitHub
Skip to content

Chapter 15: Solution for Mouse trail exercise (hint)  #541

Description

@alexpi

Hi,

I am trying to solve this exercise creating the alternative effect suggested in the hint. My version works, but the motion produced is not exactly the one required. Any suggestions or a solution?

class Dot {
  constructor(speed) {
    this.x = 0;
    this.y = 0;
    this.speed = speed;
  }
    
  create() {
    const dotEl = document.createElement('div');
    dotEl.className = 'trail';
    this.el = dotEl;
    return dotEl;
  }
}
    
const dots = [];

for (let i = 0; i < 12; i++) {
  const dot = new Dot(i + 1);
  document.body.appendChild(dot.create());
  dots.push(dot);
}

let mouse = { x: 0, y: 0 };

window.addEventListener('mousemove', event => {
  mouse.x = event.pageX - 3;
  mouse.y = event.pageY - 3;
});

const draw = (time, lastTime) => {
  dots.forEach(dot => {
    /*if (lastTime != null) { Account for frame rate differences }*/

    dot.x += (mouse.x - dot.x) / dot.speed;
    dot.y += (mouse.y - dot.y) / dot.speed;
    
    dot.el.style.left = dot.x + 'px';
    dot.el.style.top = dot.y + 'px';
  });

  requestAnimationFrame(newTime => draw(newTime, time));
}
  
requestAnimationFrame(draw);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions