Ricebandit
Ricebandit

Reputation: 353

EaselJS: Using updateCache() with AlphaMaskFilter When Dragging Mask

I'm using an imported png with an alpha gradient that I'm setting as a mask that reveals the bitmap it is assigned to. The mask object is draggable (kind of like a flashlight). I know I'm supposed to use an AlphaMaskFilter as one of the filters, and I know I'm supposed to use .updateCache()... I'm just not sure I'm using them correctly?

var stage;
var assetQueue;
var bg;
var bgMask;
var container;
var amf;

$(document).ready(function(){
    loadImages();

});

function loadImages()
{

    // Set up preload queue
    assetQueue = new createjs.LoadQueue();


    assetQueue.addEventListener("complete", preloadComplete);
    assetQueue.loadManifest([{id:"img_bg",src:"images/Nintendo-logo-red.jpg"}, {id:"img_bg_mask",src:"images/background_mask.png"}]);
}

function preloadComplete()
{
    assetQueue.removeEventListener("complete", preloadComplete);

    init();
}

function init()
{
    stage = new createjs.Stage("stage_canvas");

    setBackgrounds();

    sizeStage();

    $(document).mousemove(function(evt){
        trackMouse(evt);
    });
}

function trackMouse(evt)
{
    var mouseX = evt.pageX;
    var mouseY = evt.pageY;

    // Move the containing clip around
    container.x = mouseX - (bgMask.image.width / 2);
    container.y = mouseY - (bgMask.image.height / 2);


    // Offset the position of the masked image.
    bg.x = -container.x;
    bg.y = -container.y;

    container.updateCache();
    stage.update();
}

function setBackgrounds()
{   
    bg = new createjs.Bitmap(assetQueue.getResult("img_bg"));
    bgMask = new createjs.Bitmap(assetQueue.getResult("img_bg_mask"));
    container = new createjs.Container();

    container.addChild(bg);
    amf = new createjs.AlphaMaskFilter(bgMask.image)
    container.filters = [amf];

    container.cache(0, 0, bg.image.width, bg.image.height);

    stage.addChild(container);

    stage.update();
}

function sizeStage()
{

    var windowW = 600;
    var windowH = 600;

    stage.canvas.width = windowW;
    stage.canvas.height = windowH;

    stage.update();
}

Upvotes: 1

Views: 2965

Answers (1)

Ricebandit
Ricebandit

Reputation: 353

Solution found (for anyone interested). The key is to add the image you want to mask to a container. Move the container to any position you want, then offset the contained image within the container. The code has been updated to reflect this.

Upvotes: 2

Related Questions