Skip to content

Liven up your canvas CanvasRenderingContext2D sketches with a little animation and zero effort

Notifications You must be signed in to change notification settings

tmanderson/animated-context-2d

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Animated Context 2D

Liven up your CanvasRenderingContext2D sketches with a little animation.

Animated Context 2D aims to implement the entirety of the CanvasRenderingContext2D API.

basic exampletree example


Example

This example code is what is used in the above image. Notice it's nearly one-to-one with the pre-existing CanvasRenderingContext2D API (only difference is the specification of duration and easing function given to beginPath)

const ctx = new AnimatedContext2D(canvas); // use this EXACTLY like `Context2D`, animations are FREE!

ctx.beginPath(500, "out.cubic"); // Note: the extra arguments
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
ctx.translate(100, 100);
ctx.rotate(Math.PI/4);
ctx.lineTo(canvas.width/2, canvas.height/2);
ctx.arc(50);
ctx.lineTo(canvas.width, 0);
ctx.stroke();

API

class AnimatedContext2D(canvasElement, defaultEasing: EASE, FPS: number = 60)

  • canvasElement a HTMLCanvasElement
  • defaultEasing the default easing function to use for all paths
  • FPS frames-per-second. Defaults to 60

AnimatedContext2D.beginPath(duration: number, easing: EASE)

  • duration in milliseconds.
  • easing is any of these. Defaults to AnimatedContext2D.defaultEasing

The duration and easing are used for each path instruction. So the following

// begin a new path, with 500ms animation durations using `in.quad` easing function
ctx.beginPath(500, "in.quad");
ctx.lineTo(10, 10);
ctx.rect(0, 0, 100, 100);
ctx.fill();

would take 500ms to complete and both the lineTo and rect would use EASE.IN_QUAD.

  • LINEAR = ("linear")
  • IN_QUAD = ("in.quad")
  • OUT_QUAD = ("out.quad")
  • IN_CUBIC = ("in.cubic")
  • OUT_CUBIC = ("out.cubic")
  • IN_QUARTIC = ("in.quartic")
  • OUT_QUARTIC = ("out.quartic")
  • IN_SINE = ("in.sine")
  • OUT_SINE = ("out.sine")
  • IN_EXPO = ("in.expo")
  • OUT_EXPO = ("out.expo")

Animated Context2D Method Support

All Context2D methods are available on the AnimatedContext instance, so you can use it just as you'd use Context2D itself. The methods listed below with are those that support (or will support) animations.

  • moveTo
  • fillStyle
  • lineStyle
  • lineTo
  • arc
  • arcTo
  • lineWidth
  • lineCap
  • miterLimit
  • transform
  • translate
  • rotate
  • skew
  • rect