简体   繁体   中英

Moving object in canvas

I am stuck at a point which I don't know what to do. I am learning the basics of using the canvas element so I gave myself a little assignment. I want to place a circle on the canvas which can be pushed forward by pressing a button. So each time a button is pressed, the circle should move forward 10px. But now I am stuck for a while and I can't figure out what I do wrong. (I am also new into programming in javascript and programming overal).

This is the code I have so far

    <html>
<head></head>
<body>
<button onclick="animationStep()" id="startAnimation" style="width:200px; height:50px; color:"green";">Press here to move</button>
<canvas id="myCanvas" width="500" height="300"
        style="border: 1px dotted black">
</canvas>
<script>


   function drawDisc( x,y,r ) {
      theContext.beginPath();
      theContext.arc(x,y,r,0,Math.PI*2,false);
      theContext.closePath();
      theContext.fill();
   }

   function startDrawing(canvasId) {
      var canvasElement = document.getElementById(canvasId);
      var drawingContext = canvasElement.getContext("2d");
      return drawingContext;
   }

   var theContext = startDrawing("myCanvas")

   var x = 100; 

   function animationStep(){
       while( x <= 400 ) {
          x = x + 10;
          theContext.clearRect(0,0,500,300); 
          drawDisc( x, 100, 30 );
          console.log("animated");
       }
    }
</script>
</body>
</html>

When I look in the console log, it immediately execute the animation 36 times. I think it's stuck in the while loop but I cant figure out how to get this to work properly. Maybe I am overlooking something simple?

Thanks in regard!

Get rid of the while loop.

So

function animationStep(){
   while( x <= 400 ) {
      x = x + 10;
      theContext.clearRect(0,0,500,300); 
      drawDisc( x, 100, 30 );
      console.log("animated");
   }
}

should be

function animationStep(){
      x = x + 10;
      theContext.clearRect(0,0,500,300); 
      drawDisc( x, 100, 30 );
      console.log("animated");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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