canvashtml5-canvascreatejseaseljs

How to overlay non-transparent part of Bitmap with a color in Easeljs/Createjs?


I have an PNG image that has some transparent portion. Now I want to apply a color overlay to the non-transparent part of the image while keeping the transparent portion intact.

If I use the ColorFilter it fills the whole bitmap. I've also tried the AlphaMaskFilter (using the same PNG as source) but it doesn't work either. The whole bitmap is always filled with color.

Any other suggestions on how to do it?


Solution

  • You would have to write a filter that either:

    Here is a sample plugin using the first approach above, which is probably the most efficient:

    (function () {
        "use strict";
        function ColorMaskFilter(color) {
            this.color = color;
        }
        var p = createjs.extend(ColorMaskFilter, createjs.Filter);
        p.applyFilter = function (ctx, x, y, width, height, targetCtx, targetX, targetY) {
            if (!this.color) { return true; }
            targetCtx = targetCtx || ctx;
            if (targetX == null) { targetX = x; }
            if (targetY == null) { targetY = y; }
    
            targetCtx.save();
            if (ctx != targetCtx) {
                return false;
            }
    
            targetCtx.globalCompositeOperation = "source-out"; // Use source-in to fill the shape instead
        targetCtx.fillStyle = this.color;
            targetCtx.rect(targetX,targetY,width,height);
        targetCtx.fill();
    
            targetCtx.restore();
            return true;
        };
        p.clone = function () {
            return new AlphaMaskFilter(this.color);
        }; 
        createjs.ColorMaskFilter = createjs.promote(ColorMaskFilter, "Filter");
    }());
    

    I put together a quick fiddle using this example: http://jsfiddle.net/dbtwd463/

    Note: Edited from original which just suggested the approach to include a sample and fiddle