TweenJS Documentation

repository·master·Indexed 25 days ago

https://github.com/createjs/tweenjs

TweenJS is a lightweight JavaScript library for tweening numeric object properties and CSS styles. Designed to integrate with EaselJS but independent of it, the library provides the Tween, Timeline, and Ease classes to manage animations. It includes a centralized Ticker for heartbeats, an EventDispatcher for event management, and supports method chaining via Tween.get() to define sequences of steps and actions.

Tokens
5.9K
Snippets
14
Records
31
Agent score
86%

What's inside TweenJS

  1. Overview of TweenJS classes

    master

    TweenJS consists of three primary classes:

    • Tween: Used to create new tween instances via Tween.get().
    • Timeline: Used to synchronize and control multiple tweens as a single group.
    • Ease: Provides a collection of easing functions. Note that these functions use a single parameter representing the current linear ratio (0 to 1), rather than the standard 4-parameter signature.
  2. Configure Tween options

    master

    When creating a tween with createjs.Tween.get(target, config), you can pass an options object to customize its behavior. All properties default to false.

    • loop: If true, the tween will loop when it reaches the end.
    • useTicks: If true, the tween uses ticks for duration instead of milliseconds.
    • css: If true, enables CSS mapping for certain CSS properties.
    • ignoreGlobalPause: If true, the tween continues to tick even when the global Ticker is paused.
    createjs.Tween.get(target, {loop:true, useTicks:true, css:true, ignoreGlobalPause:true}).to(etc...);
  3. Install the MotionGuidePlugin

    master

    To use the Motion Guide plugin, you must install it after TweenJS has been loaded by calling createjs.MotionGuidePlugin.install(). This enables the guide property in your tweens.

    createjs.MotionGuidePlugin.install();
  4. Use a Motion Guide in a Tween

    master

    Once installed, you can animate an object along a defined path using the guide property within a .to() call. The path is defined as an array of coordinates used for moveTo and curveTo calls (quadratic bezier curves).

    Guide Object Properties:

    • path (Required, Array): The x/y points used to draw the path. The array must follow the pattern [x0, y0, cx1, cy1, x1, y1, cx2, cy2, x2, y2, ...] where cx/cy are control points.
    • start (Optional, 0-1): Initial position along the path (default is 0).
    • end (Optional, 0-1): Final position along the path (default is 1).
    • orient (Optional, string): Controls how the object rotates along the path:
      • "fixed": Forces the object to face down the path for all movement (relative to start rotation).
      • "auto": Rotates the object along the path relative to the line.
      • "cw": Forces clockwise rotation (Adobe Flash/Animate-like behavior).
      • "ccw": Forces counter-clockwise rotation.

    Important: Do not share guide objects between different tweens, even if the properties are identical, as the library stores internal state on these objects.

    // Using a Motion Guide
    createjs.Tween.get(target).to({guide:{ path:[0,0, 0,200,200,200, 200,0,0,0] }},7000);
  5. Create tweens with Tween.get()

    master

    Use createjs.Tween.get(target) to create a new tween instance. You can chain methods to define a sequence of steps and actions.

    Steps (defined via .to() and .wait()) have a duration and define property changes. Actions (defined via .call(), .set(), .play(), and .pause()) execute between steps without a duration.

    To override any existing tweens on a target, pass true as the third parameter to Tween.get().

    var tween = createjs.Tween.get(myTarget)
        .to({x:300},400)
        .set({label:"hello!"})
        .wait(500).to({alpha:0,visible:false},1000)
        .call(onComplete);
    
    // To remove existing tweens on the target:
    createjs.Tween.get(target, null, true);
  6. Identify the correct TweenJS library file

    master

    Depending on your environment (development vs. production) and whether you want the stable or latest version, choose from the following files:

    • tweenjs.js: The most recent tagged (stable) version of all TweenJS classes. Use this for debugging.
    • tweenjs.min.js: The most recent tagged (stable) version, minified and stripped of comments/whitespace. Use this for deployment.
    • tweenjs-NEXT.js: Contains the latest (in-progress) TweenJS classes.
    • tweenjs-NEXT.min.js: A minified version of the latest updates to the library.
  7. Manage Tween labels

    master

    Labels allow you to jump to specific points in a tween (useful for Timeline objects).

    • addLabel(label, position): Adds a named label at a specific millisecond/tick position.
    • setLabels(labels): Overwrites all existing labels with an object in the format {labelName: position}.
    • getLabels(): Returns a sorted array of {label, position} objects.
    • resolve(positionOrLabel): Converts a label string into its numeric position, or returns the numeric value if passed directly.
  8. Promote superclass methods with createjs.promote

    master

    Use createjs.promote(subclass, prefix) to create aliases for overridden superclass methods in the format prefix_methodName. It also adds an alias to the superclass constructor as prefix_constructor. This allows subclasses to call superclass methods directly without using function.call, improving performance. Call this after the subclass prototype is fully defined.

    function ClassA(name) {
    	this.name = name;
    }
    ClassA.prototype.greet = function() {
    	return "Hello " + this.name;
    }
    
    function ClassB(name, punctuation) {
    	this.ClassA_constructor(name);
    	this.punctuation = punctuation;
    }
    createjs.extend(ClassB, ClassA);
    ClassB.prototype.greet = function() {
    	return this.ClassA_greet() + this.punctuation;
    }
    createjs.promote(ClassB, "ClassA");
    
    var foo = new ClassB("World", "!?!!");
    console.log(foo.greet()); // Hello World!!!
  9. Configure the Ticker interval and framerate

    master

    The createjs.Ticker manages the timing of animations. You can control the speed of the tick using either interval (milliseconds between ticks) or framerate (frames per second).

    Note: framerate is a shortcut where framerate == 1000 / interval. These properties are ignored if the ticker is using the RAF (Request Animation Frame) timing mode.

  10. Create a new Tween with Tween.get()

    master

    Use createjs.Tween.get(target, props) to create a new tween instance. This is a cleaner alternative to new createjs.Tween(target, props) and supports method chaining.

    Parameters:

    • target (Object): The object whose properties will be animated.
    • props (Object, optional): Configuration properties for the tween instance. Supported keys include:
      • useTicks (boolean): If true, uses ticks instead of milliseconds.
      • ignoreGlobalPause (boolean): If true, the tween ignores global pauses.
      • loop (number|boolean): Number of loops (e.g., -1 for infinite).
      • reversed (boolean): Whether the tween plays in reverse.
      • bounce (boolean): Whether the tween bounces.
      • timeScale (number): Speed multiplier.
      • paused (boolean): Initial pause state.
      • position (number): Initial position in the tween.
      • onChange (Function): Callback for the change event.
      • onComplete (Function): Callback for the complete event.
      • override (boolean): If true, removes all existing tweens for the target.
    var tween = createjs.Tween.get(target).to({x:100}, 500);
  11. Measure Ticker performance with getMeasuredFPS and getMeasuredTickTime

    master

    To monitor performance, use these static methods:

    • createjs.Ticker.getMeasuredFPS([ticks]): Returns the actual frames per second. Defaults to the number of ticks per second (approx. 1 second of history).
    • createjs.Ticker.getMeasuredTickTime([ticks]): Returns the average time spent within a tick execution stack in milliseconds. Defaults to the number of ticks per second.