HTML & CSS Wiki
No edit summary
No edit summary
 
Line 1: Line 1:
 
{{DISPLAYTITLE:{{HTML tag|canvas}}}}
 
{{DISPLAYTITLE:{{HTML tag|canvas}}}}
  +
{{Infobox element
{{ElementInfobox
 
|usage = <canvas width="100" height="100"></canvas>
+
|name = {{HTML tag|canvas}}
  +
|element-type = Interactive
|example = <div id="tag-canvas-wrapper">Enable JavaScript to see the live example.</div>}}
 
  +
|html-version = HTML5
  +
|spec-version = 5.0
  +
|status = Stable
  +
|dom-interface = HTMLCanvasElement
  +
}}
 
The [[HTML]] '''<code>&lt;canvas&gt;&lt;/canvas&gt;</code>''' element can be used to draw graphics via scripting (usually [[JavaScript]]). It can be used to draw graphs, make photo compositions or even perform animations.
 
The [[HTML]] '''<code>&lt;canvas&gt;&lt;/canvas&gt;</code>''' element can be used to draw graphics via scripting (usually [[JavaScript]]). It can be used to draw graphs, make photo compositions or even perform animations.
   

Latest revision as of 07:44, 1 December 2019

The HTML <canvas></canvas> element can be used to draw graphics via scripting (usually JavaScript). It can be used to draw graphs, make photo compositions or even perform animations.

Mozilla applications gained support <canvas> starting with Gecko 1.8 (Firefox 1.5). The element was originally introduced by Apple for the OS X Dashboard and Safari. Internet Explorer, prior to version 9.0 beta, does not support <canvas>, but a page can effectively add support for it by including a script from Google's Explorer Canvas project. Opera 9 also supports <canvas>. It is currently the only way to draw graphics in vanilla javascript.


Attributes

  • width - The width of the coordinate space in CSS pixels. Default is 300.
  • height - The height of the coordinate space in CSS pixels. Default is 150.
  • See Global HTML Attributes for more.


HTML example:

<html>
 <head>
  <script type="application/x-javascript">
    function draw() {
      var canvas = document.getElementById("canvas");
      if (canvas.getContext) {
        var ctx = canvas.getContext("2d");

        ctx.fillStyle = "rgb(200,0,0)";
        ctx.fillRect (10, 10, 55, 50);

        ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
        ctx.fillRect (30, 30, 55, 50);
      }
    }
  </script>
 </head>
 <body onload="draw();">
   <canvas id="canvas" width="150" height="150">
     <p>This example requires a browser that supports the
     <a href="http://www.w3.org/html/wg/html5/">HTML5</a> 
     <canvas> feature.</p>
   </canvas>
 </body>
</html>

That produces:

Canvas in Firefox 3.6.10.

Rendering

The canvas is used as an area to draw on, but by itself does not have a visual appearance.