Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i rotate a shape in canvas,html5?

im tried to rotate a line with this

window.onload= function(){
        var canvas=document.getElementById("foo");
        var context=canvas.getContext("2d");

        context.moveTo(250, 50);
        context.lineTo(250, 250);
        context.stroke();
        context.rotate(0.30);

    };

what am i doing wrong? i think im missing some steps. can anyone explain?

like image 305
nope Avatar asked Nov 28 '22 04:11

nope


1 Answers

the rotate() actually rotates the entire coordinate system. Which defaults to 0,0 (Upper left corner of your canvas). You'd need to do something along these lines:

context.save(); // saves the coordinate system
context.translate(250,50); // now the position (0,0) is found at (250,50)
context.rotate(0.30); // rotate around the start point of your line
context.moveTo(0,0) // this will actually be (250,50) in relation to the upper left corner
context.lineTo(0,200) // (250,250)
context.stroke();
context.restore(); // restores the coordinate system back to (0,0)

Check out this link for a really good explanation of how translate() and rotate() work: tutsplus tutorial

Steve

like image 158
Steve Avatar answered Dec 09 '22 15:12

Steve