-2
\$\begingroup\$

Why my image doesn't move? Can you help me ...

<script>
   window.requestAnimFrame = (function(callback) {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
        function(callback) {
          window.setTimeout(callback, 1000 / 60);
        };
      })();

      var canvas = document.getElementById('myCanvas');
      var ctx = canvas.getContext('2d');

      ctx.font = 'bold 20pt Calibri';
      ctx.fillText('Traffic Light SIMULATION', 250, 25);

      function animate(imageObj, canvas, ctx, startTime) {
        // update
        var time = (new Date()).getTime() - startTime;

        var linearSpeed = 100;
        // pixels / second
        var newX = linearSpeed * time / 1000;

        if(newX < canvas.width - imageObj.width / 2) {
          imageObj.x = newX;
        }

        // request new frame
        requestAnimFrame(function() {
          animate(imageObj, canvas, ctx, startTime);
        });
      }      

    var imageObj = new Image();
      imageObj.onload = function() {
        ctx.save();
        ctx.translate(imageObj.width,0);
        ctx.scale(-0.5,0.5);
        ctx.drawImage(imageObj,200,100);
        ctx.restore();
      };
      imageObj.src = 'car.png';

      setTimeout(function() {
        var startTime = (new Date()).getTime();
        animate(imageObj, canvas, ctx, startTime);
      }, 2000);

</script>
\$\endgroup\$
1
  • \$\begingroup\$ You could help us helping you by giving a more detailed description of the problem in plain text, along with the code. \$\endgroup\$ Commented Jul 13, 2014 at 17:59

1 Answer 1

1
\$\begingroup\$

You have to draw the image at every frame when using canvas, you render the image once when calling ctx.drawImage, and thereafter you don't render anything to the canvas, so it stays the same.

\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.