Rotating around an arbitrary point: HTML5 Canvas

后端 未结 2 1956
生来不讨喜
生来不讨喜 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);
    

提交回复
热议问题