Canvas Start And Stop an Animation Using HTML 5

Introduction

 
In this article, we are going to understand starting and stopping an animation using HTML 5 Canvas. In this section, to start an HTML5 Canvas animation, we can call a function that repeatedly requests a new animation frame, and to stop an HTML5 Canvas animation we can simply not request a new animation frame.
 
Here we will use some JavaScript and some styles along with HTML code. Just go through the steps to see how to create this application. Let's see how the CanvasStartStopAnimation application can be created. To do so use the following steps.
 
Step 1 : Open a HTML editor or Visual Studio. Open File menu ->select new ->Choose Website
 
0000.jpg
 
This is where we will create an HTML5 application.    
  • Go to Solution Explorer
  • Right-click on the Application name
  • Select Add-->add new item
  • Now in the window that opens, select an HTML page or new Webform
  • Rename it to canvasstarstopanimation.aspx
cnst2.gif
 
Step 2: In this section, we will create the style for the media and create the .css on the media screen. Put the given script in the Head section of the HTML or between the <head>--</head> tags. Here the CSS is used for design purposes.
 
CSS Script
  1. <style>  
  2. body  
  3. {  
  4.   margin0px;  
  5.   padding0px;  
  6. }  
  7. Canvas  
  8. {  
  9.    border2px solid #9C9898;  
  10.    margin-top50px;  
  11.    margin-left50px;  
  12.    background-color#F4D19F;  
  13.    box-shadow: 5px 5px 8px #222;  
  14.  }  
  15. .title  
  16. {  
  17.    text-aligncenter;  
  18.    font-family: Segoe UI Light, ArialHelvetica;  
  19.    font-size2.2em;  
  20.    margin1em;  
  21. }  
  22. .info  
  23. {  
  24.    text-aligncenter;  
  25.    font-family: Segoe UI Light, ArialHelvetica;  
  26.    font-size1.2em;  
  27.    margin0.25em;  
  28. }  
  29. </style> 
Step 3 : In this part we need to work on some JavaScript. To fully understand how JavaScript works, download the attached .rar file and run the CanvasStartStopAnimation  application.
 
The whole JavaScript looks as in the following:
  1. <script>  
  2.         window.requestAnimFrame = (function (callback)  
  3.         {  
  4.             return window.requestAnimationFrame ||  
  5.                 window.webkitRequestAnimationFrame ||  
  6.                 window.mozRequestAnimationFrame ||  
  7.                 window.oRequestAnimationFrame ||  
  8.                 window.msRequestAnimationFrame ||  
  9.                function (callback)  
  10.                 {  
  11.                     window.setTimeout(callback, 1000 / 60);  
  12.                 };  
  13.         })();  
  14.          function drawRect(myRectangle)  
  15.          {  
  16.             var canvas = document.getElementById("myCanvas");  
  17.             var context = canvas.getContext("2d");  
  18.             context.beginPath();  
  19.             context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);  
  20.             context.fillStyle = "#8ED6FF";  
  21.             context.fill();  
  22.             context.lineWidth = myRectangle.borderWidth;  
  23.             context.strokeStyle = "black";  
  24.             context.stroke();  
  25.         }  
  26.         function animate(lastTime, myRectangle, animProp)  
  27.          {  
  28.             if (animProp.animate) {  
  29.                 var canvas = document.getElementById("myCanvas");  
  30.                 var context = canvas.getContext("2d");  
  31.                 // update  
  32.                 var date = new Date();  
  33.                 var time = date.getTime();  
  34.                 var timeDiff = time - lastTime;  
  35.                 var linearSpeed = 100;  
  36.                 // pixels / second  
  37.                 var linearDistEachFrame = linearSpeed * timeDiff / 1000;  
  38.                 var currentX = myRectangle.x;  
  39.                 if (currentX < canvas.width - myRectangle.width - myRectangle.borderWidth / 2)  
  40.                 {  
  41.                     var newX = currentX + linearDistEachFrame;  
  42.                     myRectangle.x = newX;  
  43.                 }  
  44.                 lastTime = time;  
  45.                 // clear  
  46.                 context.clearRect(0, 0, canvas.width, canvas.height);  
  47.                 // draw  
  48.                 drawRect(myRectangle);  
  49.                 // request new frame  
  50.                 requestAnimFrame(function ()  
  51.                 {  
  52.                     animate(lastTime, myRectangle, animProp);  
  53.                 });  
  54.             }  
  55.         }  
  56.         window.onload = function ()  
  57.         {  
  58.             var myRectangle = {  
  59.                 x: 0,  
  60.                 y: 50,  
  61.                 width: 100,  
  62.                 height: 50,  
  63.                 borderWidth: 5  
  64.             };  
  65.                var animProp = {  
  66.                 animate: false  
  67.             };  
  68.             // add click listener to canvas  
  69.             document.getElementById("myCanvas").addEventListener("click"function ()  
  70.             {  
  71.                 if (animProp.animate)  
  72.                 {  
  73.                     animProp.animate = false;  
  74.                 }  
  75.                 else  
  76.                  {  
  77.                     animProp.animate = true;  
  78.                     var date = new Date();  
  79.                     var time = date.getTime();  
  80.                     animate(time, myRectangle, animProp);  
  81.                 }  
  82.             });  
  83.             drawRect(myRectangle);  
  84.         };  
  85. </script> 
Step 4 : In this section, we are going to become familiar with the body part of HTML scripting. Replace this script from the body section of the canvasstarstopanimation.aspx page. Here we pass a Canvas in the canvas tag. 
  1. <body style="background-color: #C9E0E6">  
  2.     <center>  
  3.         <h1>  
  4.             Canvas Start And Stop Animation  
  5.         </h1>  
  6.     </center>  
  7.     <hr />  
  8.     <canvas id="myCanvas" width="578" height="200">  
  9.         </canvas>  
  10. </body> 
Step 5 : The complete code for the CanvasStartStopAnimation application:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="canvasstarstopanimation.aspx.cs" Inherits="_Default" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <style>  
  6.     </style>  
  7.     <script>  
  8.     </script>  
  9. </head>  
  10. <body style="background-color: #C9E0E6">  
  11.     <center>  
  12.         <h1>  
  13.             Canvas Start And Stop Animation  
  14.         </h1>  
  15.     </center>  
  16.     <hr />  
  17.     <canvas id="myCanvas" width="578" height="200">  
  18.         </canvas>  
  19. </body>  
  20. </html> 
Step 6: Output Press F5
 
Note: For the accurate output of HTML5 applications, you must have the Google Chrome browser on your PC. Click on the canvas to start and stop the animation, when the application runs on the browser.
 
cnst.gif
 
cnst1.gif
 
Here are some useful resources