javascript - how can i rotate a shape in canvas,html5? - Stack Overflow

admin2025-01-30  4

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?

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?

Share Improve this question asked May 14, 2011 at 0:01 nopenope 1,0782 gold badges15 silver badges32 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 28

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

Use this instead:

context.rotate(0.30); // <<< set current transformation to rotated
context.moveTo(250, 50);
context.lineTo(250, 250);
context.stroke();
context.rotate((Math.PI / 180) * 25); //Rotate the canvas by 25 degrees

context.save();
context.beginPath();
context.rotate((Math.PI / 180) * 25); //Rotate the canvas by 25 degrees
context.moveTo(250, 50);
context.lineTo(250, 250);
context.stroke();
context.closePath();
context.restore(); // to reset the canvas rotation

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1738245001a63409.html

最新回复(0)