如何让这个动画从右向左移动?

How do I make this animation move from right to left?

我一直在学习一些 JavaScript,这是练习之一。它工作得很好,但其中一个挑战是让动画从右到左移动,我被困在那里有一段时间了。我确定这真的很简单,但我尝试过的一切都行不通

"use strict";

var Test = {
  canvas: undefined,
  canvasContext: undefined,
  rectanglePosition: 0
};

Test.start = function() {
  Test.canvas = document.getElementById("myCanvas");
  Test.canvasContext = Test.canvas.getContext("2d");
  Test.mainLoop();
};
document.addEventListener('DOMContentLoaded', Test.start);
Test.update = function() {
  var d = new Date();
  Test.rectanglePosition = d.getTime() % Test.canvas.width;
};
Test.draw = function() {
  Test.canvasContext.fillStyle = "green";
  Test.canvasContext.fillRect(Test.rectanglePosition, 100, 50, 50);

};
Test.mainLoop = function() {
  Test.clearCanvas();
  Test.update();
  Test.draw();
  window.setTimeout(Test.mainLoop, 1000 / 60);
};

Test.clearCanvas = function() {
  Test.canvasContext.clearRect(0, 0, Test.canvas.width, Test.canvas.height);
};
<div id="testArea">
  <canvas id="myCanvas" width="800" height="480"></canvas>
</div>

您应该可以通过更改 Test.update 函数来完成此操作。

目前您正在查看 d 的秒数,并将其除以屏幕宽度并获取余数。剩下的就是确定正方形的水平位置。

如果您在更新函数之外设置变量 idirection 并调整 i 每个更新方向(+ 或 -),直到达到 0 或屏幕的宽度,你应该能够让它来回移动...查看更新:

"use strict";

var Test = {
  canvas: undefined,
  canvasContext: undefined,
  rectanglePosition: 0
};
var i = 0; //current location of the square
var direction = 1; //1 if we are going right, -1 if we are going left

Test.start = function() {
  Test.canvas = document.getElementById("myCanvas");
  Test.canvasContext = Test.canvas.getContext("2d");
  Test.mainLoop();
};
document.addEventListener('DOMContentLoaded', Test.start);
Test.update = function() {
  //var d = new Date();
  //Test.rectanglePosition = d.getTime() % Test.canvas.width;
 
  if (i <= 0) {
     direction = 1;
  } else if (i >= (Test.canvas.width - 50)) {
     //Text.canvas.width - 50 is how far you can go to the 
     //right without running the square off the screen
     //(since 50 is the width of the square)
     direction = -1;
  }
  i += direction;
  Test.rectanglePosition = i;
};
Test.draw = function() {
  Test.canvasContext.fillStyle = "green";
  Test.canvasContext.fillRect(Test.rectanglePosition, 100, 50, 50);

};
Test.mainLoop = function() {
  Test.clearCanvas();
  Test.update();
  Test.draw();
  window.setTimeout(Test.mainLoop, 1000 / 60);
};

Test.clearCanvas = function() {
  Test.canvasContext.clearRect(0, 0, Test.canvas.width, Test.canvas.height);
};
<div id="testArea">
  <canvas id="myCanvas" width="400" height="480"></canvas>
</div>