<!DOCTYPE html>
<
html
>
<
head
>
<
title
>How to Build Dynamic Graphics in HTML5</
title
>
<
script
type
=
"text/javascript"
src
=
</
script
>
</
head
>
<
body
>
<
canvas
width
=
"300"
height
=
"300"
id
=
"Canvas"
>
</
canvas
>
<
div
>
<
button
id
=
"start"
>Start</
button
>
<
button
id
=
"stop"
>Stop</
button
>
</
div
>
<
script
>
let canvas = $("#Canvas");
let context = canvas.get(0).getContext("2d");
context.fillStyle = "green";
// Width of the animation
let Width = canvas.width();
// Height of the animation
let Height = canvas.height();
let playAnimation = true;
let startButton = $("#start");
let stopButton = $("#stop");
// Code to disable Start button
startButton.hide();
startButton.click(function () {
$(this).hide();
stopButton.show();
playAnimation = true;
animate();
});
// Code to disable Stop button
stopButton.click(function () {
$(this).hide();
startButton.show();
playAnimation = false;
});
// Code to define width and height of the shape
let Shape = function (x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
// No reversal of direction in
// the x-axis initially
this.reverseX = false;
this.reverseY = false;
};
// Code to generate ten random
// shapes for animation loop
let shapes = new Array();
for (let i = 0; i <
10
; i++) {
let
x
=
Math
.random() * 300;
let
y
=
Math
.random() * 300;
let
width
=
height
= Math.random() * 30;
// Adding random shapes to canvas
shapes.push(new Shape(x, y, width, height));
};
function animate() {
context.clearRect(0, 0, Width, Height);
let
shapesLength
= shapes.length;
for (let
i
=
0
; i < shapesLength; i++) {
let
tmpshape
=
shapes
[i];
if (!tmpshape.reverseX) {
// Increment the x co-ordinate by 3 units
tmpshape.x += 3;
} else {
// Decrement the x co-ordinate by 3 units
tmpshape.x
-
=
3
;
};
if (!tmpshape.reverseY) {
// Increment the y co-ordinate by 3 units
tmpshape.y += 3;
} else {
// Decrement the y co-ordinate by 3 units
tmpshape.y
-
=
3
;
};
// Code for shapes to bounce off the boundary
context.fillRect(tmpshape.x, tmpshape.y,
tmpshape.width, tmpshape.height);
if (tmpshape.x < 0) {
tmpshape.reverseX
=
false
;
} else if (tmpshape.x + tmpshape.width > Width) {
// Reverse the direction of shape if position of
// shape is greater than width of canvas
tmpshape.reverseX = true;
};
if (tmpshape.y <
0
) {
tmpshape.reverseY
=
false
;
} else if (tmpshape.y + tmpshape.height > Height) {
// Reverse the direction of shape if position of
// shape is greater than height of canvas
tmpshape.reverseY = true;
};
};
if (playAnimation) {
setTimeout(animate, 35);
}; // Runs animate() function infinitely
// after every 35ms
};
animate();
</
script
>
</
body
>
</
html
>