Playing with vector masks

Now, we will complete our previous example to create a simple drag-and-drop example using vector masks. The idea is to change the x and y coordinates of the mask layer on the mousemove event of the parent layer so that we can only see the masked layer over the existing shape. It will seem that only a circular shape is being dragged, but what's actually happening is that our mask layer is changing continuously. The source code of our example is as follows:

var stage = new createjs.Stage("canvas");
var mask = new createjs.Shape();

mask.graphics.drawCircle(0, 0, 30);
mask.x = 100;
mask.y = 100;

var bg = new createjs.Shape();
bg.graphics.clear().beginFill("red").rect(0, 0, 400, 400);

bg.mask = mask;

function handlePress(event) {
    event.addEventListener("mousemove", handleMove);
}

function handleMove(event) {
    mask.x = stage.mouseX;
    mask.y = stage.mouseY;
    stage.update();
}

bg.addEventListener("mousedown", handlePress);

stage.addChild(bg);
stage.update();

As in the previous example, we created a mask layer in the shape of a circle in the first line. We specified the default coordinates for the mask layer with x=100 and y=100. Then, we created a bg variable that contains the background or parent layer.

Because we need the coordinates of the mask layer to change continuously as we move the mouse cursor, we bound a callback function to both mousedown and mousemove events. Then, inside the mousemove callback function, we changed the co-ordination of the mask layer and updated the stage.

The result will look like a drag-and-drop ball over the stage, but actually, it's our mask layer that keeps changing with every mouse move.

Playing with vector masks
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.54.136