Moving an image around the screen

I start in html5 and come across this problem in a simple program for moving images around the screen. This is a simple pacman program in which I used two images. One of them is a pacman with an open mouth, and the other with a closed mouth. When I tried to move it around the screen to the right, and then it should return to its original position. He tried many ways, but no one works. It moves only once for a step, and for the next step it is static. It will be really useful if anyone can solve this problem.

<html> <head> <SCRIPT> var timer = setInterval(Run,500); flag = 1; function Run(){ img1 = document.getElementById("PacMan"); var init=0; var x = 0; var dest_x = 800; var interval = 10; if(x<dest_x) x = x + interval; img1.style.left = x+"px"; if (x+interval < dest_x) img1.style.left = init+"px"; if(flag ==1){ img1.src = "PacMan2.png"; flag=0; } else { img1.src = "PacMan1.png"; flag=1; } } </SCRIPT> </head> <body> <img id="PacMan" src = "PacMan1.png" onClick=clearInterval(timer) style="position:absolute"> </img> </body> </html> 
+4
source share
4 answers

Try moving

 var init=0; var x = 0; var dest_x = 800; var interval = 10; 

to function Run(){ .

Now you are rewriting the results with the original data.

+4
source
  var timer = setInterval("Run()",500); 

you missed some commas!

0
source

Try reading the current pacMan position with

 var x = img1.offsetLeft; 
0
source

In my opinion, you should do this using Canvas (see the example on MDN) and JavaScript.

-1
source

All Articles