EaselJS - Rotate a shape around its center

Thịnh Phạm picture Thịnh Phạm · Dec 2, 2013 · Viewed 15.3k times · Source

I'm making a rotating rectangle with EaselJS but it doesn't work like I thought.

As I think, if I want to make a square (40x40) which rotates around its center at position x=100, y=100, I will need to set it's registration point to regX=20, regY=20.

//Create a stage by getting a reference to the canvas
stage = new createjs.Stage("demoCanvas");
//Create a Shape DisplayObject.
circle = new createjs.Shape();
circle.graphics.beginFill("red").drawRect(100, 100, 40, 40);
circle.regX = circle.regY = 20;
//Add Shape instance to stage display list.
stage.addChild(circle);

createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", onTick);

function onTick() {
    circle.rotation++;
    stage.update();
}

http://jsfiddle.net/ZbZjL/14/

Answer

net.uk.sweet picture net.uk.sweet · Dec 2, 2013

You're drawing the rectangle within the shape at the point 100, 100 and then setting the registration point to 20, 20 which means you're rotating a huge shape with a rectangle in one corner of it from (more or less) a point at the opposite corner.

In the following I draw the rectangle at the origin of the new shape and then place the shape itself using the x and y properties:

//Create a stage by getting a reference to the canvas
stage = new createjs.Stage("demoCanvas");
//Create a Shape DisplayObject.
circle = new createjs.Shape();
circle.graphics.beginFill("red").drawRect(0, 0, 40, 40);
circle.regX = circle.regY = 20;

circle.x = circle.y = 100;

//Add Shape instance to stage display list.
stage.addChild(circle);

createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", onTick);

function onTick() {
    circle.rotation++;
    stage.update();
}

See fiddle.