繁体   English   中英

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

[英]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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM