Creating 2-D Animations on Canvas - movement of objects

In this tutorial, you will learn:

  • How to use context.drawImage() function of HTML5 Canvas.
  • How to use two images to move a car forward and backward smoothly.
  • The distinction between displacement and distance.
Finding a good book to master HTML5 can be very challenging: there are so many around - most with eye-catching titles and very complex substance.
Therefore, Vivax Solutions strongly recommends Core HTML5 Canvas for those who really want to delve into HTML5.
Please click the image to access Amazon:

Interactive Motion of a Car

In this example, context.drawImage() method of context object is used to draw two images on canvas at positions determined by the coordinates of a point on it.

It take three arguments: a reference to the image; the coordinates of the top-left corner of the position where the image is placed on the canvas.

context.drawImage() method must be followed by the source of the image.



The Code for Interactive Car is as follows:

<script type="text/javascript">
var canvas = document.getElementById('Canvas_One');
var context = canvas.getContext('2d');
// increse the movement along the road
var a=5;
var x;
// create the image of a car on canvas
var imgObj = new Image();
// create a message on load
context.font = '20pt Calibri';
context.textAlign = 'center';
context.fillStyle = 'blue';
context.fillText('Move a Car Here!', 192, 150);
function motion() {
// initial value comes from a hidden field
x=eval(document.getElementById('h').value);
x = x + a;
// clear the canvas
context.clearRect(0, 0, 400, 300);
// draw the first image on the canvas
context.drawImage(imgObj,x,150);
// soruce of the image when conditions are met
if (x > 375) { a = -5; imgObj.src = "../images/car2.png"; }
// draw the second image on the canvas
if(x<=5){a=5;imgObj.src="../images/car1.png";}
document.getElementById('h').value=x;
context.font = '12pt Calibri';
context.textAlign = 'center';
context.fillStyle = 'blue';
// show the displacement on canvas
context.fillText('Displacement = ' + x + ' m', 125, 250);
context.fillStyle = 'purple';
// show the displacement on canvas
if (a > 0) { context.fillText('Distance = ' + x + ' m', 285, 250); }
else
{ context.fillText('Distance = ' +(750-x) + ' m', 285, 250); }
if ((750 - x) >= 740 && a < 0) { stop_one(); }
context.fillStyle = 'green';
context.font = '20pt Calibri';
context.fillText('Vector VS Scalar', 200, 40);
var xx;
function start_one(){
xx=window.setInterval('motion()',200);
}
function stop_one(){
window.clearInterval(xx);
}
</script>

 

All Canvas Animations