javascript - How do I make this animation move from right to left? -
i have been learning javascript , 1 of exercises. works fine, 1 of challenges make animation go right left , have been stuck in there while. i'm sure simple have tried doesn't work
"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>
you should able changing test.update
function.
currently looking @ seconds of d
, dividing width of screen , grabbing remainder. remainder determining horizontal position of square.
if set variable i
, direction
outside of update function , adjust i
each update direction (+ or -) until reach either 0 or width of screen should able go , forth... check out update:
"use strict"; var test = { canvas: undefined, canvascontext: undefined, rectangleposition: 0 }; var = 0; //current location of square var direction = 1; //1 if going right, -1 if 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 how far can go //right without running square off screen //(since 50 width of square) direction = -1; } += 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>
Comments
Post a Comment