Reputation: 31
For a game project, I'm drawing images using their properties such as fileName, position, scale, rotation.
Here is the part that does the drawing:
this.context.save();
this.context.translate(item.position.x, item.position.y);
if (item.rotation > 0) {
this.context.rotate(item.rotation * (Math.PI / 180));
}
if (item.scale.x !== 1 || item.scale.y !== 1) {
this.context.scale(item.scale.x, item.scale.y);
}
var width = item.imageSize.width * item.scale.x;
var height = item.imageSize.height * item.scale.y;
this.context.drawImage(this.assets.image[item.fileName], -(width / 2), -(height / 2), width, height);
this.context.restore();
(don't mind the strange positioning, it's not important)
This works fine, but there is one thing that I don't understand:
Rotation and scaling can be done in two different ways: first scale and then rotate, or other way around. Logically, one would think that first scale then rotation is correct, but for some reason, it only works correctly if I first rotate then scale.
What is the correct way of doing this?
Upvotes: 3
Views: 533
Reputation: 9845
The "correct way" really depends on what you're trying to do. For you, it seems like rotating and then scaling results in what you expect.
Here is a fiddle that shows the difference between rotating then scaling and scaling then rotating: http://jsfiddle.net/HYbC7/3/
What's unexpected for me is when you scale then rotate. If you scale(x, y)
where x
and y
are not equal, then rotate, then the rotation along the x-axis will be different than the rotation along the y-axis and the resulting grid will be skewed.
Upvotes: 1
Reputation: 35309
Where is your point of origin for your objects? Are the x/y the top left? If so that could be causing the issue.
ctx.translate(box.x, box.y);
ctx.scale(2,2);
ctx.rotate(box.angle);
ctx.translate(box.x, box.y);
ctx.rotate(box.angle);
ctx.scale(2,2);
If you notice both of those demos work fine regardless of when I perform the scaling and rotating. My point of origins however (where I translate to) are in the center of the boxes.
To answer your question (or attempt to) there is no right or wrong way, you can scale first or rotate first, its really just a matter of preference.
Upvotes: 2