• Stars
    star
    494
  • Rank 89,130 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 3 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Perfect interpolation for multiplayer cursors.

perfect-cursors

Perfect interpolation for animated multiplayer cursors. Used in tldraw.

💕 Love this library? Consider becoming a sponsor.

Edit perfect-cursors-demo

Installation

yarn add perfect-cursors
# or
npm i perfect-cursors

Introduction

You can use this library to smoothly animate a cursor based on limited information.

Kapture 2022-01-08 at 09 25 50

Above: We are updating the red cursor's position once every 80 milliseconds. The perfect-cursors library is being used to correctly animate between these positions.

Animating between points

When implementing a multiplayer app, you will most likely be displaying each user's cursor location based on the information you receive from a multiplayer service such as Pusher, Liveblocks.

In a perfect world, these updates would occur "in real time": that is, arriving with zero latency and arriving at the same rate as the user's monitor.

Kapture 2022-01-08 at 09 35 34

Above: Updating the cursor instantly.

In the real world, however, services often "throttle" their updates to roughly one update every 50-80 milliseconds.

Updating the cursors' locations directly will cause cursors to "jump" between points.

Kapture 2022-01-08 at 09 22 43

Above: Updating the cursor's once position every 80 milliseconds.

Transitioning between points via CSS can work, however this looks increasingly artificial as the delay increases. Worse, because updates do not come in on an exact interval, some animations will never finish while others will pause between animations.

Kapture 2022-01-08 at 09 31 55

Above: Transitioning the cursor's once position every 80 milliseconds.

Smart animating with JavaScript and dynamic durations can be better, however this still looks artificial as the delay increases.

Kapture 2022-01-08 at 10 11 39

Above: Animating the cursor once position every 80 milliseconds.

For best results, you would animate while interpolating the cursors' locations based on a set of connected curves (e.g. a "spline").

Kapture 2022-01-08 at 09 25 50

Above: Animating the cursor once position every 80 milliseconds using spline interpolation.

In this way, your animations can very closely approximate the actual movement of a cursor. So closely, in fact, that it appears as though the cursor is being updated "in real time" with a "one-update" delay.

Usage

Quick n' dirty docs.

Usage

To use the library directly, create an instance of the PerfectCursor class and pass it a callback to fire on each animation frame.

import { PerfectCursor } from "perfect-cursors"

const elm = document.getElementById("cursor")

function updateMyCursor(point: number[]) {
  elm.style.setProperty("transform", `translate(${point[0]}px, ${point[1]}px)`)
}

const pc = new PerfectCursor(updateMyCursor)

Use the instance's addPoint to add a point whenever you have a new one.

pc.addPoint([0, 0])
setTimeout(() => pc.addPoint([100, 100]), 80)
setTimeout(() => pc.addPoint([200, 150]), 160)

Use the dispose method to clean up any intervals.

pc.dispose()

Usage in React

To use the library in React, create a React hook called usePerfectCursor.

// hooks/usePerfectCursor

import { PerfectCursor } from "perfect-cursors"

export function usePerfectCursor(
  cb: (point: number[]) => void,
  point?: number[]
) {
  const [pc] = React.useState(() => new PerfectCursor(cb))

  React.useLayoutEffect(() => {
    if (point) pc.addPoint(point)
    return () => pc.dispose()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pc])

  const onPointChange = React.useCallback(
    (point: number[]) => pc.addPoint(point),
    [pc]
  )

  return onPointChange
}

And then a Cursor component that looks something like this:

// components/Cursor

import * as React from "react"
import { usePerfectCursor } from "../hooks/usePerfectCursors"

export function Cursor({ point }: { point: number[] }) {
  const rCursor = React.useRef<SVGSVGElement>(null)

  const animateCursor = React.useCallback((point: number[]) => {
    const elm = rCursor.current
    if (!elm) return
    elm.style.setProperty(
      "transform",
      `translate(${point[0]}px, ${point[1]}px)`
    )
  }, [])

  const onPointMove = usePerfectCursor(animateCursor)

  React.useLayoutEffect(() => onPointMove(point), [onPointMove, point])

  return (
    <svg
      ref={rCursor}
      style={{
        position: "absolute",
        top: -15,
        left: -15,
        width: 35,
        height: 35,
      }}
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 35 35"
      fill="none"
      fillRule="evenodd"
    >
      <g fill="rgba(0,0,0,.2)" transform="translate(1,1)">
        <path d="m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z" />
        <path d="m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z" />
      </g>
      <g fill="white">
        <path d="m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z" />
        <path d="m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z" />
      </g>
      <g fill={"red"}>
        <path d="m19.751 24.4155-1.844.774-3.1-7.374 1.841-.775z" />
        <path d="m13 10.814v11.188l2.969-2.866.428-.139h4.768z" />
      </g>
    </svg>
  )
}

When the user's cursor point changes, pass that information to the Cursor component.

Development

To start the development server:

  • clone this repo
  • run yarn or npm install to install dependencies
  • run yarn start or npm run start from the project root.
  • open localhost:5420 in your browser to view the example project.

Community

License

This project is licensed under MIT.

If you're using the library in a commercial product, please consider becoming a sponsor.

Author

More Repositories

1

perfect-freehand

Draw perfect pressure-sensitive freehand lines.
HTML
3,435
star
2

perfect-arrows

Draw perfect arrows between points and shapes.
TypeScript
2,515
star
3

state-designer

State management with statecharts.
HTML
619
star
4

telestrator

A disappearing drawing tool for your screen.
TypeScript
351
star
5

globs

A globs-based vector editor.
TypeScript
237
star
6

perfect-freehand-dart

Draw perfect freehand lines—in Flutter.
Dart
236
star
7

rko

A state manager with undo, redo and persistence.
TypeScript
211
star
8

gotcha

Turn your Framer prototype into its own live developer spec.
CoffeeScript
114
star
9

liquorstore

A reactive store.
TypeScript
107
star
10

kdtype

A typing game for kids.
TypeScript
71
star
11

trashly

A reactive store.
TypeScript
53
star
12

polyclip-js

A JavaScript implementation of the Greiner-Hormann clipping algorithm.
TypeScript
47
star
13

arrows-playground

A canvas-based arrows playground.
TypeScript
37
star
14

state-designer-ide

A design environment for State Designer.
TypeScript
34
star
15

framer-moreutils

Expand Utils with some handy helper functions.
JavaScript
31
star
16

framework

A general-purpose component kit for Framer.
JavaScript
30
star
17

fontloader

Painlessly, reliably load local and web fonts into Framer prototypes.
CoffeeScript
30
star
18

arena-2022

An isometric game.
TypeScript
25
star
19

finder-toolbar-shortcuts

Easy shortcuts for Finder's toolbar.
Rich Text Format
25
star
20

react-motion-asteroids

An astroids-like game in React using Framer Motion.
TypeScript
24
star
21

personal-blog

A personal blog.
TypeScript
24
star
22

figma-plugin-perfect-freehand

A Figma plugin for drawing perfect freehand strokes.
TypeScript
24
star
23

replisketch

A collaborative drawing app built with Replicache.
TypeScript
19
star
24

framer-tools

Do good stuff fast in Framer X from the command line.
JavaScript
18
star
25

framer-controller

Control a Framer X component through overrides.
TypeScript
18
star
26

framer-button

A customizable button class for Framer prototypes.
CoffeeScript
15
star
27

tetris-react-state-designer

A Tetris implementation using React and State Designer.
TypeScript
14
star
28

framer-sublime-text

A Framer UI / Color Scheme / Syntax for Sublime Text
14
star
29

brush-engine

A brush engine for the browser.
TypeScript
13
star
30

together

A multiplayer experience.
TypeScript
13
star
31

inventory-react-state-designer

An inventory system in React and State Designer.
TypeScript
12
star
32

framer-md

A Material Design UI kit for Framer.
JavaScript
12
star
33

short-story

Small, self-contained interactive component demos.
JavaScript
12
star
34

framer-icon

Create SVG icons using this very simple module.
CoffeeScript
10
star
35

react-turtle

Turtle Graphics for React.
JavaScript
10
star
36

olc_rust_sketches

Learning rust with the olc Pixel Game Engine.
Rust
10
star
37

gnrng

A minimal seeded random number generator.
TypeScript
10
star
38

ActionLayer

An ActionLayer extends Layer, adding properties and functions designed to simplify managing events in Framer.
CoffeeScript
9
star
39

react-decal

A miniature canvas game engine in React.
TypeScript
9
star
40

quick-docs

Docs, quick.
JavaScript
8
star
41

framer-layout

Layout with grids in Framer.
CoffeeScript
8
star
42

arena-game

A tactical combat game in React.
TypeScript
6
star
43

react-use-maho

A state management tool based on statecharts.
TypeScript
6
star
44

snowcraft

Snowcraft brood war by Steve Ruiz.
TypeScript
6
star
45

FocusComponent

Control events among a group of layers.
CoffeeScript
5
star
46

state-designer-examples

Created with CodeSandbox
TypeScript
5
star
47

flow-docs

Docs for the flow component
JavaScript
4
star
48

MonokaiFade

Example of the monokai.nl-style fade effect.
TypeScript
3
star
49

perfect-freehand-signature

A pressure-based vector signature component.
3
star
50

learn-docs

Docs for the Learn Design System
JavaScript
3
star
51

bendy-arrows-playground

Created with CodeSandbox
TypeScript
3
star
52

short-story-sjs

Beautiful component previews for design, docs and demos.
TypeScript
2
star
53

unstyled-challenge

Design the web with strict limits on style.
JavaScript
2
star
54

steveruizok.github.io

UI/UX Portfolio
CSS
2
star
55

react-iso-engine

Isometric world engine written in React.
TypeScript
2
star
56

docs-mdx-cms

JavaScript
2
star
57

nextjs-content-starter

A Next.js static site with MDX.
TypeScript
2
star
58

brushy-brushy

TypeScript
2
star
59

stencil-refuge

App running on Refuge Restrooms API, built in Stencil.
JavaScript
1
star
60

emoji-picker-site

A tiny site for emoji picking.
CSS
1
star
61

st-lookbook

Webcomponents for previewing other components.
TypeScript
1
star
62

stencil-router-redux-demo

An example stencil project with stencil-router and stencil-redux working together.
HTML
1
star
63

framer-atomic-tutorial

Designing with progressive complexity, step-by-step in Framer.
JavaScript
1
star
64

react-use-three

React Hooks for three.js
TypeScript
1
star
65

docs-sites

Collection of small docs sites.
JavaScript
1
star
66

ds-docs-starter

A starter for design system documentation.
JavaScript
1
star
67

component-preview

A micro storybook-like environment for previewing components.
TypeScript
1
star
68

exp-apollo-hooks-todo

Apollo's todo list example with Apollo hooks.
JavaScript
1
star
69

framer-loupe-data

Nice website for designing with data at Framer Loupe.
JavaScript
1
star