canvashtml5-canvascreatejseaseljs

Is it possible to add a Gradient Filter to a Bitmap with EaselJS?


I have a Bitmap inside of a Container. The Container has all the transform properties (these properties are dynamic, they are fetched from the server).

// Container
const display = new createjs.Container();
display.x = 103;
display.y = 44;
display.scaleX = 0.34;
display.scaleY = 0.5;
display.rotation = 35;

// Bitmap
const bitmap = new createjs.Bitmap("trophy.png");

display.addChild(bitmap);

I would like to apply a Gradient Filter to the Bitmap, similar to how I can apply a Color Filter: I would like the end result

bitmap.filters = [
  new createjs.ColorFilter(0,0,0,1, 0,0,255,0)
];

Is this possible? I tried using AlphaMaskFilter but it doesn't seem to be working.

Thank you.


Solution

  • The approach you are looking for is to use the image as a mask for the gradient. As you suspected, you can do this with AlphaMaskFilter.

    1. Load an image
    2. Create your gradient shape
    3. Add the image as the source for the AlphaMaskFilter
    4. Apply the filter to the shape
    5. Cache the shape to apply the filter. Remember that the image you are using must be completely loaded into the cache, otherwise the filter will fail.
    var s = new createjs.Shape();
    var b = referenceToImage;
    s.graphics.beginLinearGradientFill(["#000","#069"], [0, 1], 0, 0, b.width, b.height)
        .drawRect(b.x, b.y, b.width, b.height);
    
    s.filters = [
     new createjs.AlphaMaskFilter(img)
    ];
    
    s.cache(b.x,b.y,b.width,b.height);
    

    Here is a quick fiddle using an image with an alpha channel :D https://jsfiddle.net/lannymcnie/m1zps3w7/11/