JSFiddle - React, Tailwind, and code Playground

my first easing chain

by greg gorlen

JavaScript

// fixing flex coords: https://stackoverflow.com/questions/22429864/cursor-position-with-flexbox-isnt-accurate

"use strict";

const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
document.body.margin = 0;
canvas.width = innerWidth * 0.99 | 0;
canvas.height = innerHeight * 0.96 | 0;

const Point = function (x, y) {
  this.x = x;
  this.y = y;
  this.vx = 0;
  this.vy = 0;
  this.size = 5;
  this.spring = 0.045;
  this.friction = 0.7;
  this.gravity = 0.2;
  this.repulsion = 7;
}

Point.prototype.moveTowards = function (x, y) {
  let ax = (x - this.x) * this.spring;
  let ay = (y - this.y) * this.spring;
  this.vx += ax;
  this.vy += ay;
  //this.vy += this.gravity;
  this.vx *= this.friction;
  this.vy *= this.friction;
  this.x += this.vx;
  this.y += this.vy;
};

Point.prototype.draw = function (ctx) {
  ctx.beginPath();
  ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
  ctx.fill();
};

let collide = function (a, b) {
  let dx = a.x - b.x;
  let dy = a.y - b.y;
  let distance = Math.sqrt(dx * dx + dy * dy);
  if (distance < a.size + b.size) {
  
    // Find the unit vectors 
    let ux = dx / distance;
    let uy = dy / distance;

    // Multiply the collided balls' velocities by 
    // the unit vector and repulsion factor
    a.vx -= ux * a.repulsion;
    a.vy -= uy * a.repulsion;
    b.vx += ux * b.repulsion;
    b.vy += uy * b.repulsion;
    return true;
  }
  return false;
};


const pts = 160;
let ctx = canvas.getContext("2d");
ctx.lineWidth = 8;
let mouse = { 
  x: canvas.width / 3, 
  y: canvas.height / 5 
};
let points = [];
for (let i = 0; i < pts; i++) {
  points.push(new Point(canvas.width / 2+ i * 10, canvas.height / 2 + i * 10));
}

document.addEventListener("mousemove", function (e) {
  mouse.x = e.x;
  mouse.y = e.y;
});

(function update() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  points[0].moveTowards(mouse.x, mouse.y);
  for (let i = 1; i < points.length; i++) {
   ...