5

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/

Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
Thịnh Phạm
  • 2,528
  • 5
  • 26
  • 39

1 Answers1

8

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.

Johnston
  • 20,196
  • 18
  • 72
  • 121
net.uk.sweet
  • 12,444
  • 2
  • 24
  • 42
  • 1
    Thank you. I was misunderstanding the method drawRect(x,y,w,h). x, y is not circle.x and circle.y. – Thịnh Phạm Dec 03 '13 at 00:06
  • Thanks to this example, I found that the key to correct rotation of the rectangle around it's center point lies in the distinction between the Shape DisplayObject and the Rectangle nested in that shape object. Both have their own x, y, width and height. Only the Shape DisplayObject) has a registration point. Rotating the Rectangle around this registration point requires the Rectangle center point to align with the DisplayObject registration point. This is done by drawing the rectangle at the `x: 0, y: 0` point in the DisplayObject. – Pim Schaaf Jul 07 '16 at 09:27
  • 3
    Suggestion: labeling a rotating rectangle `circle` might be confusing to some readers. Perhaps `rotating` would be a more accurate variable name for the Shape DisplayObject in this example. – Pim Schaaf Jul 07 '16 at 09:27