Warning:
This wiki has been archived and is now read-only.

Elements/canvas

From HTML Wiki
Jump to: navigation, search

<canvas> Element

A <canvas> element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, or other visual images on the fly.

HTML reference

This element was introduced in HTML5 - 4.8.10 The canvas element.

Examples

A square in a canvas [try it]:

<canvas id="myCanvas" width="300" height="300">
Your user agent does not support the HTML5 Canvas element.
</canvas>
<script>
var myCanvas = document.getElementById("myCanvas");
var canvasContext = myCanvas.getContext("2d");
canvasContext.fillRect(100, 100, 100, 100);
</script>

Multiple circles of different colors in a canvas [try it]:

<canvas id="myCanvas" width="600" height="600">
Your user agent does not support the HTML5 Canvas element.
</canvas>
<script>
var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d");
var w = myCanvas.width, h = myCanvas.height;
var i = 0;
do {
  ctx.fillStyle = "rgb(" + Math.round(255*Math.random()) + ","
                  + Math.round(255*Math.random()) + ","
                  + Math.round(255*Math.random()) + ")";
  ctx.beginPath();
  ctx.arc(w*Math.random(), h*Math.random(),
          50*Math.random(),
          0, Math.PI*2, true);
  ctx.closePath();
  ctx.fill();
} while (++i != 1000);
</script>

One can work at the pixel level in a canvas [try it]:

<canvas id="myCanvas" width="600" height="600">
Your user agent does not support the HTML5 Canvas element.
</canvas>
<script>
var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d");
var output = ctx.createImageData(myCanvas.width, myCanvas.height);
var length= output.data.length;
// output.data is an array of RGBA values
for (var i = 0; i < length; i++) {
  output.data[i] = Math.round(255*Math.random());
}
ctx.putImageData(output, 0, 0);
</script>

HTML Attributes

  • height = non-negative integer
    The height of the canvas, in CSS pixels.
  • width = non-negative integer
    The width of the canvas, in CSS pixels.

See also global attributes.

IDL Attributes and Methods

The following IDL attributes and methods are exposed to dynamic scripts.

  DOMString toDataURL(in optional DOMString type, in any... args);

  object getContext(in DOMString contextId);

See also the HTML Canvas 2D Context specification.

Accessibility

Authors should ensure that the information and user interface components must be presentable to users in ways they can perceive (WCAG 2.0 - Principle 1: Perceivable).

Work in still in progress proper technical support in HTML5.

See Also