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

时间:2015-06-19 13:27:03

标签: javascript html5 animation html5-canvas

我一直在学习一些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>

1 个答案:

答案 0 :(得分:1)

您应该可以通过更改project_id功能来执行此操作。

目前,您正在查看Test.update的秒数,并将其除以屏幕宽度并抓住剩余部分。剩下的就是确定广场的水平位置。

如果您在更新功能之外设置变量di,并使用方向(+或 - )调整每个更新direction,直到您达到0或宽度为0屏幕你应该能够让它来回...查看更新:

i
"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);
};

相关问题