Search code examples
javascriptcolorscreatejseaseljs

Change color of shape without recreating


I have a project using easelJS in that I'm trying to simply change the color of a shape object. I have a couple of examples but they both seem to indicate I would need to completely redraw the shape with a graphics.beginFill() call again. This seems completely overkill considering that I've stored my shape object already and am able to perform other manipulations on it. I've also tried to use ColorFilter and ColorMatrix but have not had luck making a clean color change. In some cases the color essentially "overwrites" the detail of the shape.

I have an array of ShapeObject that I store the createjs.Shape() object in.

    var ShapeObject = function() 
    {
            this.name;
            this.shape;
            this.rotation;
            this.color;
    };

sObject = new ShapeObject();

myShape = new createjs.Shape();
sObject.shape = myShape;

shapes = new Array();
shapes.push(sObject);

Later I am able to retrieve the shape from the array and apply a filter, for example,

    s = shapes[i];
    filter = new createjs.ColorFilter(0,0,0,1, 255,128,0,0);
    s.shape.filters = [ filter ];

Using this same example I'd like to avoid having to completely recreate the shape. I have tried the following but, while it changes color, I lose all the other details of the shape that was originally applied.

    s.shape.graphics.clear().beginFill(color);

Does anyone have an idea of how to simply change the color without completely recreating the original shape?

EDIT

Following the answer regarding .command and the createjs command blog post I have created the following.

    var theShape = new createjs.Shape();

    var fillCommand = theShape.graphics.beginFill("yellow").command;

    theShape.graphics.setStrokeStyle(1)
        .beginStroke(createjs.Graphics.getRGB(0, 0, 0))
        .drawCircle(0, 0, 20)
        .moveTo(0,-20)
        .lineTo(0,0)
        .moveTo(0,0)
        .lineTo(20,0);

    fillCommand.style = "orange";

Despite being nearly identical to the examples I am receiving the error Uncaught TypeError: Cannot set property 'style' of undefined at the last line above.


Solution

  • I wouldn't use ColorFilter or ColorMatrix, it will likely be much slower. But you could use the Graphics command object, check out the docs: http://www.createjs.com/docs/easeljs/classes/Graphics.html

     var fillCommand = myGraphics.beginFill("red").command;
     // ... later, update the fill style/color:
     fillCommand.style = "blue";