最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin17PV0评论

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

Post a comment

comment list (0)

  1. No comments so far