Simple HTML5 Canvas Animation

PraveenKumar Purushothaman

PraveenKumar Purushothaman

@praveenkumar-66Ze92 Oct 25, 2024
Hi friends,
I thought of sharing a simple canvas animation to make a ball bounce within a square. We are going to use MooTools library in this. Okay, we have three parts:
1. HTML
2. CSS
3. JavaScript

Lets start with the HTML (just the <body> content):
<body>
    <div id="container">
        <h2>Simple HTML5 Canvas Animation</h2>
        <canvas id="myCanvas" width="300" height="300"></canvas>
    </div>
</body>
Lets do some styling using CSS:
body {font: 11pt/14pt Segoe UI, Myriad Pro, Calibri, Tahoma;}
#container {text-align: center;}
#myCanvas {background: #fff; border: 1px solid #cbcbcb; text-align: center;}

Now comes the JavaScript part (Just the onLoad JS):
var context;
var dx = 4;
var dy = 4;
var y = 150;
var x = 10;
function draw(){
    context = myCanvas.getContext('2d');
    context.clearRect(0, 0, 300, 300);
    context.beginPath();
    context.arc(x, y, 20, 0, Math.PI*2, true);
    context.closePath();
    context.fill();
    if (x < 0 || x > 300)
        dx=-dx;
    if (y < 0 || y > 300)
        dy = -dy;
        x += dx;
        y += dy;
    }
setInterval(draw,10); 

Now the complete code with linking the MooTools library... 😀
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>Simple HTML5 Canvas Animation</title>
    <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/mootools/1.4.1/mootools-yui-compressed.js/js/lib/mootools-core-1.4.2-full-nocompat.js'></script>
    <style type='text/css'>
        body {font: 11pt/14pt Segoe UI, Myriad Pro, Calibri, Tahoma;}
        #container {text-align: center;}
        #myCanvas {background: #fff; border: 1px solid #cbcbcb; text-align: center;}
    </style>
<script type='text/javascript'>
window.addEvent('load', function() {
    var context;
    var dx = 4;
    var dy = 4;
    var y = 150;
    var x = 10;
    function draw(){
        context = myCanvas.getContext('2d');
        context.clearRect(0, 0, 300, 300);
            context.beginPath();
        context.arc(x, y, 20, 0, Math.PI*2, true);
        context.closePath();
        context.fill();
        if (x < 0 || x > 300)
            dx=-dx;
        if (y < 0 || y > 300)
            dy = -dy;
        x += dx;
        y += dy;
    }
    setInterval(draw,10);
});
//]]> 
</script>
</head>
<body>
    <div id="container">
        <h2>Basic Canvas Example</h2>
        <canvas id="myCanvas" width="300" height="300"></canvas>
    </div>
</body>
</html>

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform