Animating images in HTML5 and canvas

37,850

Solution 1

Try this very basic demo of a canvas animation:

http://jsfiddle.net/bDQ6b/2/

window.addEventListener('load', function () {
  var
    img = new Image,
    ctx = document.getElementById('myCanvas').getContext('2d');

  img.src = 'http://www.gravatar.com/avatar/a1f80339c0cef95be6dc73e0ac510d5d?s=32&d=identicon&r=PG';
  img.addEventListener('load', function () {

    var interval = setInterval(function() {
      var x = 0, y = 0;

      return function () {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        ctx.drawImage(img, x, y);

        x += 1;
        if (x > ctx.canvas.width) {
          x = 0;
        }
      };
    }(), 1000/40);
  }, false);
}, false);

There is a lot which could be done better though. E.g.:

  • using requestAnimationFrame instead of an interval

  • preloading the images in a more convenient way

  • using velocities and time differences (from last to current frame) instead of fixed increments

  • and many more

but, as all this would make the example way too complicated, I'll leave it as it is and hope you'll read up on those topics while learning.

Solution 2

To animate with canvas you need to record the location of your object and then increment it on a new frame setInterval(draw, 1000 / 25); allows you to run a function after a specified time interval. You could use this function to update the position of your object on the page each time a new frame is rendered.

For example:

function draw() { playersShip.move(); }

Where the move function increments or decrements the x and/or y coordinate of your object. This line draws a the specified image at a specified coordinate (which is updated when each frame is rendered).

ctx.drawImage(shipImage, playersShip.position.x, playersShip.position.y);

It would be a good idea to isolate the movement of your objects from your framerate if your building a game or similar. I can provide more in-depth samples if you need them.

Using this idea you should be able to create the animation of your image.

Solution 3

Here is the simple example bounce ball animation inside the canvas on HTML5 canvas.

 <body>
<canvas id="Canvas01" width="400" height="400" style="border:5px solid #FF9933; margin-left:10px; margin-top:10px;"></canvas>

<script>
  var canvas = document.getElementById('Canvas01');
  var ctx = canvas.getContext('2d');
  var p = {x:25, y:25};
  var velo=6, corner=30, rad=20;
  var ball={x:p.x, y:p.y};

  var moveX=Math.cos(Math.PI/180*corner) * velo;
  var moveY=Math.sin(Math.PI/180*corner) * velo;


  function DrawMe() {
  ctx.clearRect(0,0,canvas.width, canvas.height);

  if(ball.x>canvas.width-rad || ball.x<rad) moveX=-moveX;
  if(ball.y>canvas.height-rad || ball.y<rad) moveY=-moveY;

    ball.x +=moveX;
    ball.y +=moveY;

  ctx.beginPath();
  ctx.fillStyle = 'blue';
  ctx.arc(ball.x, ball.y, rad, 0 , Math.PI*2,false);
  ctx.fill();
  ctx.closePath();
  }

  setInterval(DrawMe,30);

 </script>
</body>

you can try it yourself here : http://codetutorial.com/examples-canvas/canvas-examples-bounce-ball

Share:
37,850
user1281566
Author by

user1281566

Updated on November 02, 2020

Comments

  • user1281566
    user1281566 over 3 years

    I need help with making an image float onto the canvas in HTML5 and JavaScript. I have been googling around and have not found anything. I can draw shapes on the screen but I dont know how to animate them. I want couple of different images to float in on the canvas from different directions. Can someone please help me with this? after 4 hours of googling all I could do was this

    <script type = "Text/JavaScript">
                    function Animate(){
                    var canvas=document.getElementById("myCanvas"); 
                    var ctx=canvas.getContext("2d"); 
    
                    var img = new Image();
    
                    img.onload = function ()
                    {
                        ctx.drawImage(img,20,20,300,300);
    
                    };
                    img.src = "vb.png";
                    }
                 </script> 
        </head> 
    <body> 
    <canvas id="myCanvas" height="200" width="800"></canvas>
    <br><button onclick="Animate();">Restart</button>
    

    There seem to be plenty of tutorials on animating shapes but I want to load up my own pictures and have them fly in onto the canvas.

  • oldboy
    oldboy over 5 years
    how would one go about isolating the movement from fps?