简体   繁体   中英

how to rotate a shape using rotation matrix?

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??

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM