【问题标题】:HTML5 rotating an image with canvasHTML5 使用画布旋转图像
【发布时间】:2011-08-19 14:50:16
【问题描述】:

如何使用画布的“旋转”功能围绕图像中心旋转图像,而不是围绕原点旋转。

考虑以下示例:

<html>
    <head></head>
    <body>
        <canvas id="tmp" style="width: 300px; height: 300px; border: 1px red solid" />
        <script type="text/javascript">
            var deg = 0;

            function Draw() {
                var ctx = document.getElementById('tmp').getContext('2d');

                ctx.save();
                ctx.fillStyle = "white";
                ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height);
                ctx.fillStyle = "red";

                ctx.rotate(deg * 0.0174532925199432957); //Convert to rad's
                ctx.fillRect(50, 50, 20, 20);
                ctx.restore();

                deg+=5;

                setTimeout("Draw()", 50);
            }

            Draw();
        </script>
    </body>
</html>

在本例中,红色方块在 0,0 处围绕原点旋转。假设我想围绕它的中心旋转正方形。我尝试使用 translate 将其移动到原点然后旋转,然后再次使用 translate 将其移回,如下所示:

        ctx.translate(-(50 + 10), -(50 + 10));    //Move to origin
        ctx.rotate(deg * 0.0174532925199432957); //rotate
        ctx.translate(50, 50);    //move back to original location
        ctx.fillRect(50, 50, 20, 20);
        ctx.restore();

但看起来对 translate 函数的调用会覆盖以前的 translate 并且不组合转换。那怎样才能达到我想要的效果呢?

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    这就是你要找的:jsFiddle

    //Move to center of rectangle
    ctx.translate(60, 60);
    ctx.rotate(deg * 0.0174532925199432957); //rotate
    //Draw rectangle
    ctx.fillRect(-10, -10, 20, 20);
    ctx.restore();
    

    请注意,您应该使用 Math.PI/180 而不是那个大的小数。
    我还在画布上正确设置了您的widthheight,并将您的setTimeout 更改为不使用eval()

    【讨论】:

      猜你喜欢
      • 2011-12-26
      • 1970-01-01
      • 2019-11-18
      • 1970-01-01
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      • 2015-10-01
      相关资源
      最近更新 更多