New Command approach to EaselJS Graphics

The Graphics class in EaselJS has remained largely unchanged since it was first introduced in v0.2. It worked by generating an immutable list of generic command objects that would draw vector graphics into a context.

In EaselJS v0.8.0, we did some major re-modeling. Instead of using generic command objects, we now use specific objects for each command type. For example, we now have Graphics.Fill and Graphics.Circle objects. These objects expose properties that describe the command, which can be read and changed whenever you’d like.

You can still use the familiar, chainable API for drawing, but you can now use the command property to grab a reference to the most recent command object to modify later. For example:

var fillObj = myShape.graphics.beginFill("red").command;
myShape.graphics.drawCircle(0, 0, 100);
//... later, we can change the color:
fillObj.style = "green";

If you’d like, you can also instantiate commands directly, and append them to the instructions list. This requires a little more understanding of how drawing working under the hood though (see the docs for more info):

var circleObj = new createjs.Graphics.Circle(0, 0, 100);
var fillObj = new createjs.Graphics.Fill("red");
myShape.graphics.append(Graphics.beginCmd)
    .append(circleObj)
    .append(fillObj);

Besides providing a slight performance boost, this new approach is handy for a number of reasons.

  1. modifying existing graphics (as above)
  2. introspecting the graphics list (as used by the SVGExporter)
  3. sharing commands between different Graphics objects (for example, sharing a fill between different shapes)
  4. tweening or animating graphics properties
  5. creating custom command objects to extend Graphics capabilities

In addition to this core change, we’ve done additional work to speed up graphics performance and added the new store() / unstore() method for use with cache().

5 thoughts on New Command approach to EaselJS Graphics

Comments are closed.

    • Yep, there is a performance boost, because nothing needs to be created. Earlier approaches required the entire shape object to be reconstructed, whereas here we are just changing some properties. The actual stage draw, which is required will be the bigger concern, and it remains the same for both approaches.

      Cheers.

  1. Great to see the new stuff. There is one thing that I am struggling with. Using a SVG path to draw a Graphic. At present there doesnt seem to be a way to do this so I am creating a Bitmap by using the SVG as a URI. But I would still like to draw it as a graphic over which I can have more control.

    • Currently there is no way to interpret SVG as Graphics. You can do the opposite (export Graphics to SVG), but right now your only option to get the SVG onto the Canvas is via Bitmap as you have suggested.

© Copyright 2024