Reputation:
i'm trying to rotate a square in canvas by javascript using rotation matrix. here is my code.
function square() {
this.cord=[[0,0],[-25,25],[25,25],[25,-25],[-25,-25]];
}
var a=new square();
function rotate() {
var cos=Math.sqrt(2)/2;
var sin=Math.sqrt(2)/2;
for(var j=0;j<a.cord.length;j++) {
a.cord[j][0]=a.cord[j][0]*cos-(a.cord[j][1])*sin;
a.cord[j][1]=a.cord[j][1]*cos+(a.cord[j][0])*sin;
}
}
but weird things happen and the square shrinks gradually and it doesn't rotate correctly.
what's wrong with my code??
Upvotes: 3
Views: 989
Reputation: 16007
You need to pull out the values a.cord[j][0]
and a.cord[j][1]
before calculating. Your calculation of a.cord[j][1]
is based on the freshly-calculated new value, not the original one.
So:
for(...)
{
var x = a.cord[j][0];
var y = a.cord[j][1];
a.cord[j][0] = x*cos - y*sin;
a.cord[j][1] = y*cos + x*sin;
}
Upvotes: 2