Home > Articles > Web Development > HTML/CSS

  • Print
  • + Share This
From the author of Feature #8: canvas Is an HTML Element

Feature #8: canvas Is an HTML Element

Because canvas is an HTML element, and because you can layer HTML elements by manipulating their z-index attributes, it's easy to combine HTML elements. For example, the application shown in Figure 3 uses a semi-transparent DIV on top of a canvas. That DIV contains a link to start or stop animation of the canvas.

Figure 3 A DIV element floating above a canvas.

Here's an excerpt of the HTML for the application in Figure 3:

<head>
   <style>
      #glasspane {
         position: absolute;
         left: 50px;
         top: 50px;
         padding: 0px 20px 10px 10px;
         background: rgba(0, 0, 0, 0.3);
         border: thin solid rgba(0, 0, 0, 0.6);
         color: #eeeeee;
         font-family: Droid Sans, Arial, Helvetica, sans-serif;
         font-size: 12px;
         cursor: pointer;
         -webkit-box-shadow: rgba(0,0,0,0.5) 5px 5px 20px;
         -moz-box-shadow: rgba(0,0,0,0.5) 5px 5px 20px;
         box-shadow: rgba(0,0,0,0.5) 5px 5px 20px;
         z-index: 1;
      }
   </style>
</head>

<body>
   <div id='glasspane'>
      <h2 class='title'>Bouncing Balls</h2>

      <p>One hundred balls bouncing</p>

      <a id='startLink'>Start</a>
   </div>

   <canvas id='canvas' width='750' height='500'>
      Canvas not supported
   </canvas>

   <script src='example.js'></script>
</body>

The application's JavaScript facilitates the communication between the Start link and the Canvas:

var context = document.getElementById('canvas').getContext('2d'),
    startLink = document.getElementById('startLink'),
    glasspane = document.getElementById('glasspane'),
    paused;

startLink.onclick = function(e) {
   paused = ! paused;
   startLink.innerText = paused ? 'Start' : 'Stop';
};
...

In the application shown in Figure 3, I positioned a DIV inside a canvas. You can also do the inverse, positioning canvases inside of DIVs (or other HTML elements), as the application in Figure 4 illustrates.

Figure 4 Sliders implemented with canvas elements.

The application in Figure 4 contains four canvases positioned inside a DIV. Each canvas is an interactive slider that dynamically modifies the color displayed in the color patch on the right.

Because canvas is an HTML element, you can use it with other HTML elements for all kinds of interesting use cases.

  • + Share This
  • 🔖 Save To Your Account