Explore Generating Visualisations Using JavaScript in HTML5

Generating visualizations

 
In HTML5 we will learn a wide variety of advanced functionality over what HTML was originally capable of. The most powerful aspect of HTML5 is the HTML5 canvas. The canvas element is a drawable region defined in HTML code with height and width attributes. JavaScript code can access the canvas through a full set of drawing functions allowing for dynamically generated graphics. The first thing to do is to check that the browser fully supports this.
 
Step 1: Open any HTML editor (ex. Visual Studio, Notepad, etc) and in the source code page (the page where you want to write the HTML code) type the following lines.
  1. <head>  
  2.     <meta charset=utf-8>  
  3.         <title>Liquid Particles canvas experiment </title>  
  4.         <meta name="description" content="HTML5/canvas demo." />  
  5.         <meta name="keywords" content="html5,canvas,javascript,particles,interactive,velocity,programming,flash" />  
  6.         <script type="text/javascript" src="liquid-particles.js"></script>  
  7.         <link rel="stylesheet" type="text/css" href="experiment-pages.css" />  
  8.     </head>  
Step 2: In this example there are some functions we have to use, which are given below.
 
function init() : This JavaScript function is used to initialize the canvas application.
  1. function init() {  
  2.  canvas = document.getElementById("mainCanvas");  
  3.  if (canvas.getContext) {  
  4.   setup();  
  5.   setInterval(run, 33);  
  6.   trace('Move your mouse around the page to have the particles follow the cursor, click the mouse button to send the particles flying in the other direction.<br>More here: <a href="/">/C-sharpcorner</a> |; <  
  7.    a href = "/"  
  8.    target = "_blank" > Arjun < /a>');  
  9.   }  
  10.   else {  
  11.    trace("Sorry, needs a recent version of Chrome, Firefox, Opera, Safari, or Internet Explorer 9.");  
  12.   }  
  13.  }  
function setup() : Here we have to setup the mouse direction on canvasDiv.
  1. function setup() {  
  2.  outerDiv = document.getElementById("outer");  
  3.  canvasDiv = document.getElementById("canvasContainer");  
  4.  ctx = canvas.getContext("2d");  
  5.  var i = numMovers;  
  6.  while (i--) {  
  7.   var m = new Mover();  
  8.   m.x = canvasW * 0.5;  
  9.   m.y = canvasH * 0.5;  
  10.   m.vX = Math.cos(i) * Math.random() * 34;  
  11.   m.vY = Math.sin(i) * Math.random() * 34;  
  12.   movers[i] = m;  
  13.  }  
  14.  mouseX = prevMouseX = canvasW * 0.5;  
  15.  mouseY = prevMouseY = canvasH * 0.5;  
  16.  document.onmousedown = onDocMouseDown;  
  17.  document.onmouseup = onDocMouseUp;  
  18.  document.onmousemove = onDocMouseMove;  
  19. }  
  20. function run(): Run the mouse.  
  21. function run() {  
  22.  ctx.globalCompositeOperation = "source-over";  
  23.  ctx.fillStyle = "rgba(8,8,12,0.65)";  
  24.  ctx.fillRect(0, 0, canvasW, canvasH);  
  25.  ctx.globalCompositeOperation = "lighter";  
  26.  mouseVX = mouseX - prevMouseX;  
  27.  mouseVY = mouseY - prevMouseY;  
  28.  prevMouseX = mouseX;  
  29.  prevMouseY = mouseY;  
function OnDocMouseMove() : It is used to move the mouse direction.
  1. function onDocMouseMove(e) {  
  2.  var ev = e ? e : window.event;  
  3.  mouseX = ev.clientX - outerDiv.offsetLeft - canvasDiv.offsetLeft;  
  4.  mouseY = ev.clientY - outerDiv.offsetTop - canvasDiv.offsetTop;  
  5. }  
  6. function OnDocMouseDown(): It is used to set the mouse direction to down.function onDocMouseDown(e) {  
  7.  isMouseDown = true;  
  8.  return false;  
  9. }  
  10. function OnDocMouseUp(): It is used to set the mouse direction to up.function onDocMouseUp(e) {  
  11.  isMouseDown = false;  
  12.  return false;  
  13. }  
  14. function Mover(): Used to set the mouse movement randomly.function Mover() {  
  15.  this.color = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")";  
  16.  this.y = 0;  
  17.  this.x = 0;  
  18.  this.vX = 0;  
  19.  this.vY = 0;  
  20.  this.size = 1;  
  21. }  
function rect() : Chooses the rectangular context.
  1. function rect(context, x, y, w, h) {  
  2.  context.beginPath();  
  3.  context.rect(x, y, w, h);  
  4.  context.closePath();  
  5.  context.fill();  
  6.  
function trace() : Set the doucment output.
  1. function trace(str) {  
  2.  document.getElementById("output").innerHTML = str;  
  3. }  
Step 3: Here, we have to use the try and catch to handle the error in JavaScript.
  1. <script type="text/javascript">  
  2.     try {  
  3.         var pageTracker = _gat._getTracker("UA-11054609-1");  
  4.         pageTracker._trackPageview();  
  5.     } catch (err) { }  
  6. </script>   
Step 4: Now before previewing the output in the browser you need to check whether the format that you include for multiple format files in your browser support all the tags. See the source code below to know which format is supported by which browser.
 
This is the complete source code.
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3.     <head>  
  4.         <meta charset=utf-8>  
  5.             <title>Liquid Particles canvas experiment </title>  
  6.             <meta name="description" content="HTML5/canvas demo." />  
  7.             <meta name="keywords" content="html5,canvas,javascript,particles,interactive,velocity,programming,flash" />  
  8.             <script type="text/javascript" src="liquid-particles.js"></script>  
  9.             <link rel="stylesheet" type="text/css" href="experiment-pages.css" />  
  10.         </head>  
  11.         <body>  
  12.             <div id="outer">  
  13.                 <div id="canvasContainer">  
  14.                     <canvas id="mainCanvas" width="1000" height="560"></canvas>  
  15.                     <div id="output"></div>  
  16.                 </div>  
  17.             </div>  
  18.             <script type="text/javascript">  
  19.     /** 
  20.     *   Liquid particles canvas experiment 
  21.     *   ?2010 spielzeugz.de  
  22.     */  
  23.     (function () {  
  24.          var PI_2 = Math.PI * 2;   
  25.         var canvasW = 1000;  
  26.         var canvasH = 560;  
  27.         var numMovers = 600;  
  28.         var friction = 0.96;  
  29.         var movers = [];  
  30.         var canvas;  
  31.         var ctx;  
  32.         var canvasDiv;  
  33.         var outerDiv;  
  34.         var mouseX;  
  35.         var mouseY;  
  36.         var mouseVX;  
  37.         var mouseVY;  
  38.         var prevMouseX;  
  39.         var prevMouseY;  
  40.         var isMouseDown;  
  41. function init() {  
  42.             canvas = document.getElementById("mainCanvas");  
  43.             if (canvas.getContext) {  
  44.                 setup();  
  45.                 setInterval(run, 33);  
  46.                 trace('Move your mouse around the page to have the particles follow the cursor, click the mouse button to send the particles flying in the other direction.  
  47.                 <br>More here:   
  48.                     <a href="/">/Csharpcorner</a> |;   
  49.                     <a href="/" target="_blank">Arjun</a>');  
  50.             }  
  51.             else {  
  52.                 trace("Sorry, needs a recent version of Chrome, Firefox, Opera, Safari, or Internet Explorer 9.");  
  53.             }  
  54.         }  
  55. function setup() {  
  56.             outerDiv = document.getElementById("outer");  
  57.             canvasDiv = document.getElementById("canvasContainer");  
  58.             ctx = canvas.getContext("2d");  
  59.             var i = numMovers;  
  60.             while (i--) {  
  61.                 var m = new Mover();  
  62.                 m.x = canvasW * 0.5;  
  63.                 m.y = canvasH * 0.5;  
  64.                 m.vX = Math.cos(i) * Math.random() * 34;  
  65.                 m.vY = Math.sin(i) * Math.random() * 34;  
  66.                 movers[i] = m;  
  67.             }  
  68.             mouseX = prevMouseX = canvasW * 0.5;  
  69.             mouseY = prevMouseY = canvasH * 0.5;  
  70.            document.onmousedown = onDocMouseDown;  
  71.             document.onmouseup = onDocMouseUp;  
  72.             document.onmousemove = onDocMouseMove;  
  73.         }  
  74. function run() {  
  75.             ctx.globalCompositeOperation = "source-over";  
  76.             ctx.fillStyle = "rgba(8,8,12,0.65)";  
  77.             ctx.fillRect(0, 0, canvasW, canvasH);  
  78.             ctx.globalCompositeOperation = "lighter";  
  79.             mouseVX = mouseX - prevMouseX;  
  80.             mouseVY = mouseY - prevMouseY;  
  81.             prevMouseX = mouseX;  
  82.             prevMouseY = mouseY;  
  83.              var toDist = canvasW * 0.86;  
  84.             var stirDist = canvasW * 0.125;  
  85.             var blowDist = canvasW * 0.5;  
  86.             var Mrnd = Math.random;  
  87.             var Mabs = Math.abs;  
  88.             var i = numMovers;  
  89.             while (i--) {  
  90.                 var m = movers[i];  
  91.                 var x = m.x;  
  92.                 var y = m.y;  
  93.                 var vX = m.vX;  
  94.                 var vY = m.vY;  
  95.                 var dX = x - mouseX;  
  96.                 var dY = y - mouseY;  
  97.                 var d = Math.sqrt(dX * dX + dY * dY) || 0.001;  
  98.                 dX /= d;  
  99.                 dY /= d;  
  100.                  if (isMouseDown) {  
  101.                     if (d < blowDist) {  
  102.                         var blowAcc = (1 - (d / blowDist)) * 14;  
  103.                         vX += dX * blowAcc + 0.5 - Mrnd();  
  104.                         vY += dY * blowAcc + 0.5 - Mrnd();  
  105.                     }  
  106.                 }  
  107.                  if (d < toDist) {  
  108.                     var toAcc = (1 - (d / toDist)) * canvasW * 0.0014;  
  109.                     vX -= dX * toAcc;  
  110.                     vY -= dY * toAcc;  
  111.                 }  
  112.                 if (d < stirDist) {  
  113.                     var mAcc = (1 - (d / stirDist)) * canvasW * 0.00026;  
  114.                     vX += mouseVX * mAcc;  
  115.                     vY += mouseVY * mAcc;  
  116.                 }  
  117.                 vX *= friction;  
  118.                 vY *= friction;  
  119.                 var avgVX = Mabs(vX);  
  120.                 var avgVY = Mabs(vY);  
  121.                 var avgV = (avgVX + avgVY) * 0.5;  
  122.                  if (avgVX < .1) vX *= Mrnd() * 3;  
  123.                    if (avgVY < .1) vY *= Mrnd() * 3;  
  124.                 var sc = avgV * 0.45;  
  125.                 sc = Math.max(Math.min(sc, 3.5), 0.4);  
  126.                 var nextX = x + vX;  
  127.                 var nextY = y + vY;  
  128.                 if (nextX > canvasW) {  
  129.                     nextX = canvasW;  
  130.                     vX *= -1;  
  131.                 }  
  132.                 else if (nextX < 0) {  
  133.                     nextX = 0;  
  134.                     vX *= -1;  
  135.                 }  
  136.                 if (nextY > canvasH) {  
  137.                     nextY = canvasH;  
  138.                     vY *= -1;  
  139.                 }  
  140.                 else if (nextY < 0) {  
  141.                     nextY = 0;  
  142.                     vY *= -1;  
  143.                 }  
  144.                 m.vX = vX;  
  145.                 m.vY = vY;  
  146.                 m.x = nextX;  
  147.                 m.y = nextY;  
  148.                 ctx.fillStyle = m.color;  
  149.                 ctx.beginPath();  
  150.                 ctx.arc(nextX, nextY, sc, 0, PI_2, true);  
  151.                 ctx.closePath();  
  152.                 ctx.fill();  
  153.             }  
  154.         }  
  155. function onDocMouseMove(e) {  
  156.             var ev = e ? e : window.event;  
  157.             mouseX = ev.clientX - outerDiv.offsetLeft - canvasDiv.offsetLeft;  
  158.             mouseY = ev.clientY - outerDiv.offsetTop - canvasDiv.offsetTop;  
  159.         }  
  160. function onDocMouseDown(e) {  
  161.             isMouseDown = true;  
  162.             return false;  
  163.         }  
  164. function onDocMouseUp(e) {  
  165.             isMouseDown = false;  
  166.             return false;  
  167.         }  
  168. function Mover() {  
  169.             this.color = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")";  
  170.             this.y = 0;  
  171.             this.x = 0;  
  172.             this.vX = 0;  
  173.             this.vY = 0;  
  174.             this.size = 1;  
  175.         }  
  176. function rect(context, x, y, w, h) {  
  177.             context.beginPath();  
  178.             context.rect(x, y, w, h);  
  179.             context.closePath();  
  180.             context.fill();  
  181.         }  
  182. function trace(str) {  
  183.             document.getElementById("output").innerHTML = str;  
  184.         }  
  185.         window.onload = init;  
  186.     })();  
  187.     var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");  
  188.     document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));  
  189.                 </script>  
  190.                 <script type="text/javascript">  
  191.     try {  
  192.         var pageTracker = _gat._getTracker("UA-11054609-1");  
  193.         pageTracker._trackPageview();  
  194.     } catch (err) { }  
  195. </script>  
  196.             </body>  
  197.         </html>  
Output : 
 
liquid.jpg
 
Resources
 
Here are some useful resources: