HTML Tag Reference - HTML tag <canvas>








The <canvas> element is a drawing surface that we drive using JavaScript. The canvas element is simple. All of its functionality is exposed through a JavaScript object.

Browser compatibility

<canvas> Yes 9.0 Yes Yes Yes

What's new in HTML5

The <canvas> tag is new in HTML5.

Attribute

height
Set the height in pixels for the canvas
width
Set the width in pixels for the canvas

Global Attributes

The <canvas> tag supports the Global Attributes in HTML.





Event Attributes

The <canvas> tag supports the Event Attributes in HTML.

Default CSS Settings

None.

Example

The width and height attributes specify the size of the canvas.

<!DOCTYPE HTML>
<html>
<head>
<style>
canvas {<!--   ww  w  .j  a  v  a 2 s .  co  m-->
      border: medium double black;
      margin: 4px
}
</style>
</head>
<body>
      <canvas width="500" height="200"> 
           Your browser doesn't support the <code>canvas</code> element 
      </canvas>
</body>
</html>

Click to view the demo





Draw with canvas

The following code creates a canvas tag and use Javascript to draw a rectangle on it.

<!DOCTYPE HTML>
<html>
<head>
<style>
canvas {<!--from www.  j  a v  a  2s.co  m-->
      border: medium double black;
      margin: 4px
}
</style>
</head>
<body>
      <canvas id="canvas" width="500" height="100"> 
            Your browser doesn't support the <code>canvas</code> element 
    </canvas>
      <script>
            var ctx = document.getElementById("canvas").getContext("2d");
            ctx.fillRect(10, 10, 50, 50);
      </script>
</body>
</html>

Click to view the demo