Skip to content

Dynamics.trackVelocity()

Quietly measures how fast a CSS property is changing in real-time. It doesn't animate anything by itself.

This is how you connect user interactions (like dragging) to physics (like throwing).


1. Reading Live Velocity

As you drag the box, the tracker calculates the exact speed (in pixels per second) for x and y.

Drag the box!
VX: 0px/s
VY: 0px/s
60 FPS
js
import { Dynamics } from 'animx/dynamics'
import { Interactable } from 'animx/interactable'

const tracker = Dynamics.trackVelocity('.box', 'x,y');

Interactable.create('.box', {
  onDrag() {
    console.log("X Speed:", tracker.get('x'));
    console.log("Y Speed:", tracker.get('y'));
  }
});

2. Velocity-Driven UI

You can use the live speed to change other things, like color, scale, or blur. Flick this box left and right really fast to make it turn red!

Flick the box left and right!
60 FPS
js
const tracker = Dynamics.trackVelocity('.box', 'x');

Interactable.create('.box', {
  onDrag() {
    const speed = Math.abs(tracker.get('x'));
    if (speed > 1000) {
      document.querySelector('.box').style.background = 'red';
    }
  }
});

3. The Handoff (Throwing)

The most common use is grabbing the exact speed right when the user releases an element, and then using that speed in Dynamics.throwTo.

Throw the ball around the room!
60 FPS
js
let tracker;
let throwEngine;

Interactable.create('.ball', {
  onPress() {
    if (throwEngine) throwEngine.kill();
    tracker = Dynamics.trackVelocity('.ball', 'x,y');
  },
  onRelease() {
    throwEngine = Dynamics.throwTo('.ball', {
      x: { velocity: tracker.get('x') },
      y: { velocity: tracker.get('y') }
    });
    tracker.kill(); // Cleanup
  }
});

Properties & Methods

MethodDescription
get(property)Gets the current speed of the property in pixels/sec (or degrees/sec for rotation). Positive means it's moving right/down. Negative means left/up.
kill()Stops tracking. Always call this when you are done (like when the user lets go) to save memory.