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

180 views Asked by At

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.

2

There are 2 answers

0
Lanny On BEST ANSWER

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/

0
Lanny On

After thinking about it more, there is a much more performant and simple way to get your effect: Use composite operation. AlphaMaskeFilter actually uses this behind the scenes (in Context2D), but if you do it yourself you have a little more control.

Same first steps as the caching approach I posted earlier, but instead of caching, its just one line of code.

  1. Load the bitmap
  2. Create the gradient overlay
  3. Add the bitmap to the stage, followed by the gradient
  4. Set the compositeOperation to the gradient shape so that it draws using "source-in". The shape and gradient must overlap.
s.compositeOperation = "source-in"

From the docs:

The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent.

This is much simpler in code. Here is an updated fiddle: https://jsfiddle.net/lannymcnie/jm5df4kz/1/

Also, since this is no longer cached, you can do fun things like animate the gradient. https://jsfiddle.net/lannymcnie/cjhdn18L/