Search code examples
javascriptfiltercolorsbitmapeaseljs

EaseJS applying Color filter to Bitmap


I use easeJS in the implementation of the game robolucha, currently we display different colors of the characters by using shapes under transparent images.

We want to use Bitmaps and apply color filters to it.

Sadly the ColorFilter is not working.

The Fiddle is here for the code : https://jsfiddle.net/athanazio/7z6mqnrk/

And here is the code I´m using

var stage = new createjs.Stage("filter");
var head = new createjs.Container();
head.x = 300;
head.y = 300;
head.regX = 100; 
head.regY = 100; 
var path = "https://raw.githubusercontent.com/hamilton-lima/javascript-samples/master/easejs/colorfilter/"; 

var layer1 = new createjs.Bitmap(path + "layer1-green.png");
layer1.image.onload = function(){
        layer1.filters = [ new createjs.ColorFilter(0, 0, 0, 1, 0, 0, 255, 1) ];
        layer1.cache(0,0,200,200);
}

var layer2 = new createjs.Bitmap(path + "layer2.png");

head.addChild(layer1);
head.addChild(layer2);

stage.addChild(head);

createjs.Ticker.addEventListener("tick", headTick);
function headTick() {
        head.rotation += 10;
}

createjs.Ticker.addEventListener("tick", handleTick);
function handleTick() {
        stage.update();
}    

Solution

  • The ColorFilter does not work in this example because the image is being loaded cross-domain. The browser will not be able to read the pixels to apply the filter. I am not exactly sure why there is no error in the console.

    EaselJS has no mechanism to automatically handle cross-origin images when it creates images behind the scenes (which it does when you pass a string path). You will have to create the image yourself, set the "crossOrigin" attribute, and then set the path (in that order). Then you can pass the image into the Bitmap constructor.

    var img = document.createElement("img");
    img.crossOrigin = "Anonymous";
    img.onload = function() {
        // apply the filter and cache it
    }
    img.src = path + "layer1.png";
    
    layer1 = new createjs.Bitmap(img);
    

    You don't have to wait for the image to load to create the Bitmap and apply the filter, but you will have to wait to cache the image.

    This fix also requires a server that sends a cross-origin header, which git does. Here is an updated fiddle with that change. Note that if your image is loaded on the same server, this is not necessary.

    https://jsfiddle.net/7z6mqnrk/10/

    Cheers.