1 // target frames per second
2 const FPS = 30;
3 var x = 0;
4 var y = 0;
5 var xDirection = 1;
6 var yDirection = 1;
7 var image = new Image();
8 image.src = "http://javascript-tutorials.googlecode.com/files/jsplatformer1-smiley.jpg";
9 var canvas = null;
10 var context2D = null;
11
12 window.onload = init;
13
14 function init()
15 {
16 canvas = document.getElementById('canvas');
17 context2D = canvas.getContext('2d');
18 setInterval(draw, 1000 / FPS);
19 }
20
21 function draw()
22 {
23 context2D.clearRect(0, 0, canvas.width, canvas.height);
24 context2D.drawImage(image, x, y);
25 x += 1 * xDirection;
26 y += 1 * yDirection;
27
28 if (x >= 450)
29 {
30 x = 450;
31 xDirection = -1;
32 }
33 else if (x <= 0)
34 {
35 x = 0;
36 xDirection = 1;
37 }
38
39 if (y >= 250)
40 {
41 y = 250;
42 yDirection = -1;
43 }
44 else if (y <= 0)
45 {
46 y = 0;
47 yDirection = 1;
48 }
49 }