Rotating around an arbitrary point: HTML5 Canvas

后端 未结 2 1932
生来不讨喜
生来不讨喜 2020-12-29 08:11

Come see the amazing disappearing rectangle!

But seriously I have a really simple HTML5 canvas that just draws a rectangle(using lineTo instead of rect for a

相关标签:
2条回答
  • 2020-12-29 08:41

    To rotate around a point you need to do 3 steps.

    • First translate the context to the center you wish to rotate around.
    • Then do the actual rotation.
    • Then translate the context back.

    Like this:

    var canvas = document.getElementById("testCanvas");
    var dc     = canvas.getContext("2d");
    var angle = 0;
    window.setInterval(function(){
        angle = (angle + 1) % 360;
        dc.clearRect(0, 0, canvas.width, canvas.height);
    
        dc.save();
        dc.fillStyle = "#FF0000";
    
        dc.translate(150,200); // First translate the context to the center you wish to rotate around.
        dc.rotate( angle*Math.PI/180 ); // Then do the actual rotation.
        dc.translate(-150,-200); // Then translate the context back.
    
        dc.beginPath();
        dc.moveTo(100, 100);
        dc.lineTo(200, 100);
        dc.lineTo(200,300);
        dc.lineTo(100,300);
        dc.closePath();
        dc.fill();
    
        dc.restore();
    }, 5);
    
    0 讨论(0)
  • 2020-12-29 08:51

    When you rotate the canvas, it rotates from the origin (0, 0), so your rectangle ends up getting rotated off the screen.

    See this example where it's only rotated 45 deg: http://jsfiddle.net/wjLSm/

    One way to fix this is to translate the canvas by its width & height/2: http://jsfiddle.net/wjLSm/1/ (then 0,0 is at the middle -- be aware of this)

    0 讨论(0)
提交回复
热议问题