use-animated-canvas

[home][package][repo]

A React hook to create a canvas element with a built-in render loop.
Useful for creating animations, games, and other interactive graphics.

Installation


    npm install @ihtnc/use-animated-canvas
  

Usage


    import { use2dAnimatedCanvas } from '@ihtnc/use-animated-canvas'

    const App = () => {
      const { Canvas } = use2dAnimatedCanvas({
        render: (context, data) => {
          // this function gets called every frame
          // use context to draw on the canvas
          // use data to access details like frame count, fps, etc
          // data can also include a user-defined value if supplied
        }
      })

      return <Canvas />
    };
  

Animation

The HTML canvas element allows us to render objects (images, lines, shapes, text, etc) through code. Animation in a canvas is achieved by rendering a series of images (frames) in quick succession. This gives the illusion of movement (think [zoetrope]).

The [@ihtnc/use-animated-canvas] package provides React hooks as a way to create animations by calling various handlers to render a single frame in a canvas HTML element. The hook will then start a loop (render loop) that calls each of these handlers perpetually.

The idea is that by adding some logic, the handlers will "slightly modify" the frame rendered to the canvas on each iteration. And since the loop calls these handlers in rapid succession, the image rendered on the canvas will appear to animate.

Rendering loop

Below are handlers exposed by the hook and the order in which they are called in the render loop. Every handler except `initialiseData` is called on each iteration of the render loop.

HandlerPurpose
-initialiseDatafor initialising data
1preRenderTransformfor transforming data before any rendering operations
2globalFilterfor applying filter operations on all layers
3renderBackgroundFilterfor applying filter operations on the background layer
4renderBackgroundfor rendering elements on the background layer
5renderFilterfor applying filter operations on the main layer
6renderfor rendering elements on the main layer
7renderForegroundFilterfor applying filter operations on the foreground layer
8renderForegroundfor rendering elements on the foreground layer
9postRenderTransformfor transforming data before the next frame

Stay a while and listen...

This is a port of the rendering framework developed as part of the [canvas-concoctions] project. It has since then been modified to add more features, refactor functionalities, and fix several issues.