Hello Everyone!
Today we are going to learn something about the HTML5 canvas tag. And the result we are trying to achieve is shown here at codepan, It would be a ball moving around a designated area. The complete code is also available here on github.
So let’s begin and create an HTML file called index.html (You could name it anything else, it doesn’t matter) and put the following code in that:
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <title>Moving Ball</title> </head> <body> <canvas id="my_canvas" width="300" height="300">Get Chrome...</canvas> </body> </html> |
Now, if you open the above index.html file containing the code mentioned above in your browser, it would not display anything. Though, the canvas is there, we just can’t see it yet.
So, in order to make use of the canvas tag that we’ve already introduced, we need to make use of some javascript. Let’s paint the entire canvas area as black and then paint a circle on top of it. Let’s add below code in your <head> tag:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<head> <meta charset="UTF-8"> <title>Moving Ball</title> <script> window.onload = function(){ var canvas = document.getElementById("my_canvas"); c = canvas.getContext("2d"); c.fillStyle = "black"; c.fillRect(0, 0, canvas.width, canvas.height); c.fillStyle = "white"; c.beginPath(); c.arc(100,100,10,0,2 * Math.PI,false); c.fill(); }; </script> </head> |
Now, if you reload/ reopen the index.html file, you should be able to see a circle drawn on a black background (of area 300 x 300).
Let’s fast forward to the final code and update the code between your script tags to below code and reload the page to get the final result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<script> function getRandomInt(max, min){ return Math.floor(Math.random() * (+max - +min)) + +min; } window.onload = function(){ var canvas = document.getElementById("my_canvas"); c = canvas.getContext("2d"); TWO_PI = 2 * Math.PI; radius = 5; var randomX =getRandomInt(0,1); var randomY =getRandomInt(0,1); // document.write("Random Number Generated : " + random ); var posX = getRandomInt(0, canvas.width); var posY = getRandomInt(0, canvas.height); var incX = randomX == 0 ? -1 : 1; var incY = randomY == 0 ? -1 : 1; setInterval(function(){ c.fillStyle = "rgba(0,0,0,0.1)"; c.fillRect(0, 0, canvas.width, canvas.height); if(posX + radius > canvas.width || (posX < radius && incX == -1)){ incX = -incX; } if(posY + radius > canvas.height || (posY < radius && incY == -1)){ incY = -incY; } posX += incX; posY += incY; c.fillStyle = "white"; c.beginPath(); c.arc(posX,posY,radius,0,TWO_PI,false); c.fill(); }, 10); }; </script> |