【问题标题】:Why is this just rotating and not moving to the right?为什么这只是旋转而不向右移动?
【发布时间】:2022-02-28 22:00:28
【问题描述】:

我有以下网页:

var box_x = 30;
var box_y = 30;
var box_width = 30;
var box_height = 30;
var box_direction = 20; // Degrees clockwise

function draw_box() {
  var c = document.getElementById("area");
  var ctx = c.getContext("2d");
  ctx.clearRect(0, 0, 500, 500);
  ctx.rotate(box_direction * Math.PI / 180);
  ctx.fillRect(box_x, box_y, 100, 50);
  box_x += 2;
}

setInterval(draw_box, 1000);
<h1>Welcome</h1>
<canvas id="area" width="500px" height="500px" style="border: 1px solid #0000aa" />
</canvas>

为什么盒子不向右移动?

【问题讨论】:

  • 您似乎误解了rotate 的作用。它正在向右移动。你只是不断改变“正确”的位置。
  • 你想让盒子向右移动吗?是否也需要轮换?那么 box_direction 是什么?
  • 你打电话给rotate(),你为什么期望它向右移动?
  • 盒子方向是盒子的角度
  • box_x += 2; 虽然这会移动盒子

标签: javascript html


【解决方案1】:

ctx.rotate 从左上角旋转整个画布,所以你应该首先使用 ctx.translate 将左上角移动到枢轴(这是盒子的 左上角),然后做同样的事情,但相反,这样你就可以重置画布的旋转和平移

var box_x = 30;
var box_y = 30;
var box_width = 30;
var box_height = 30;
var box_direction = 20; // Degrees clockwise

function draw_box() {
  var c = document.getElementById("area");
  var ctx = c.getContext("2d");
  ctx.clearRect(0, 0, 500, 500);

  ctx.translate(box_x, box_y);
  ctx.rotate(box_direction * Math.PI / 180);
  ctx.fillRect(0, 0, 100, 50);
  ctx.rotate(-box_direction * Math.PI / 180);
  ctx.translate(-box_x, -box_y);

  box_x += 2;
}

setInterval(draw_box, 1000);
<h1>Welcome</h1>
<canvas id="area" width="500px" height="500px" style="border: 1px solid #0000aa" />
</canvas>

【讨论】:

    【解决方案2】:

    因为你有ctx.rotate(box_direction * Math.PI / 180);。这是随着盒子旋转的。

    <html>
      <head>
        <title>Rectangles wandering around aminlessly</title>
      </head>
      <body
    <h1>Welcome</h1>
    <canvas id="area" width="500px" height="500px" style="border: 1px solid #0000aa"/>
    </canvas>
    
    <script lang="javascript">
    
    var box_x = 30;
    var box_y = 30;
    var box_width = 30;
    var box_height = 30;
    var box_direction = 20; // Degrees clockwise
    
    function draw_box() {
      var c = document.getElementById("area");
      var ctx = c.getContext("2d");
      ctx.clearRect(0, 0, 500, 500);
      ctx.fillRect(box_x, box_y, 100, 50);
      box_x += 2;
    }
    
    setInterval(draw_box, 1000);
    
    
    </script>
    </body>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-19
      • 1970-01-01
      相关资源
      最近更新 更多