Drawing graphics with canvas

  • Revision slug: HTML/Canvas/Drawing_Graphics_with_Canvas
  • Revision title: Drawing Graphics with Canvas
  • Revision id: 75283
  • Created:
  • Creator: Nickolay
  • Is current revision? No
  • Comment /* A Simple Example */ fix

Revision Content

Introduction

With the Firefox 1.1 Developer Preview Release, Firefox includes a new HTML element for programmable graphics. <canvas> is based on the WhatWG canvas specification, which itself is based on Apple's <canvas> implemented in Safari. It can be used for rendering graphs, UI elements, and other custom graphics on the client.

<canvas> creates a fixed size drawing surface that exposes one or more rendering contexts. We'll focus on the 2D rendering context (incidentally, the only currently defined rendering context). In the future, other contexsts may provide different types of rendering; for example, a 3D context based on OpenGL ES.

The 2D Rendering Context

A Simple Example

To start off, here's a simple example that draws two intersecting rectangles, one of which has alpha transparency:

Example 1.

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

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

 ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
 ctx.fillRect (30, 30, 50, 50);
}
  </script>
 </head>
 <body onload="init()">
   <canvas id="canvas" width="300" height="300"></canvas>
 </body>
</html>

The draw function gets the canvas element, then obtains the 2d context. The ctx object can then be used to actually render to the canvas. The example simply fills two rectangles, by setting fillStyle to two different colors using CSS color specifications and calling fillRect. The second fillStyle uses rgba() to specify an alpha value along with the color.

The fillRect, strokeRect, and clearRect calls render a filled, outlined, or clear rectangle. To render more complex shapes, paths are used.

Using Paths

The beginPath function starts a new path, and moveTo, lineTo, arcTo, arc, and similar methods are used to add segments to the path. The path can be closed using closePath. Once you have a path is created, you can use fill or stroke to render the path to the canvas.

Example 2.

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

  ctx.fillStyle = "red";

  ctx.beginPath();
  ctx.moveTo(30, 30);
  ctx.lineTo(150, 150);
  ctx.quadraticCurveTo(60, 70, 70, 150);
  ctx.lineTo(30, 30);
  ctx.fill();
}
   </script>
 </head>
 <body onload="draw()">
   <canvas id="canvas" width="300" height="300"></canvas>
 </body>
</html>

Calling fill() or stroke() causes the current path to be used. To be filled or stroked again, the path must be recreated.

Graphics State

Attributes of the context such as fillStyle, strokeStyle, lineWidth, and lineJoin are part of the current graphics state. The context provides two methods, save() and restore(), that can be used to move the current state to and from the state stack.

A More Complicated Example

Here's a little more complicated example, that uses paths, state, and also introduces the current transformation matrix. The context methods translate(), scale(), and rotate() all transform the current matrix. All rendered points are first transformed by this matrix.

Example 3.

 <html>
  <head>
   <script type="application/x-javascript">
 function drawBowtie(ctx, fillStyle) {
 
   ctx.fillStyle = "rgba(200,200,200,0.3)";
   ctx.fillRect(-30, -30, 60, 60);
 
   ctx.fillStyle = fillStyle;
   ctx.globalAlpha = 1.0;
   ctx.beginPath();
   ctx.moveTo(25, 25);
   ctx.lineTo(-25, -25);
   ctx.lineTo(25, -25);
   ctx.lineTo(-25, 25);
   ctx.closePath();
   ctx.fill();
 }
 
 function dot(ctx) {
   ctx.save();
   ctx.fillStyle = "black";
   ctx.fillRect(-2, -2, 4, 4);
   ctx.restore();
 }
 
 function draw() {
   var canvas = document.getElementById("canvas");
   var ctx = canvas.getContext("2d");

   // note that all other translates are relative to this
   // one
   ctx.translate(45, 45);

   ctx.save();
   //ctx.translate(0, 0); // unnecessary
   drawBowtie(ctx, "red");
   dot(ctx);
   ctx.restore();
 
   ctx.save();
   ctx.translate(85, 0);
   ctx.rotate(45 * Math.PI / 180);
   drawBowtie(ctx, "green");
   dot(ctx);
   ctx.restore();
 
   ctx.save();
   ctx.translate(0, 85);
   ctx.rotate(135 * Math.PI / 180);
   drawBowtie(ctx, "blue");
   dot(ctx);
   ctx.restore();
 
   ctx.save();
   ctx.translate(85, 85);
   ctx.rotate(90 * Math.PI / 180);
   drawBowtie(ctx, "yellow");
   dot(ctx);
   ctx.restore();
 }
    </script>
  </head>
  <body onload="draw()">
    <canvas id="canvas" width="300" height="300"></canvas>
  </body>
 </html>

This defines two methods, drawBowtie and dot, that are called 4 times. Before each call, translate() and rotate() are used to set up the current transformation matrix, which in turn positions the dot and the bowtie. dot renders a small black square centered at (0, 0). That dot is moved around by the transformation matrix. drawBowtie renders a simple bowtie path using the passed-in fill style.

As matrix operations are cumulative, save() and restore() are used around each set of calls to restore the original canvas state. One thing to watch out for is that rotation always occurs around the current origin; thus a translate() rotate() translate() sequence will yield different results than a translate() translate() rotate() series of calls.

Revision Source

<h3 name="Introduction"> Introduction </h3>
<p>With the <a href="en/Deer_Park">Firefox 1.1 Developer Preview Release</a>, Firefox includes a new
HTML element for programmable graphics.  <code>&lt;canvas&gt;</code> is based on the 
<a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/#graphics">WhatWG canvas specification</a>,
which itself is based on Apple's <code>&lt;canvas&gt;</code> implemented in
Safari.  It can be used for rendering graphs, UI elements, and other
custom graphics on the client.
</p><p><code>&lt;canvas&gt;</code> creates a fixed size drawing surface that exposes
one or more <i>rendering contexts</i>.  We'll focus on the 2D rendering
context (incidentally, the only currently defined rendering context).
In the future, other contexsts may provide different types of
rendering; for example, a 3D context based on OpenGL ES.
</p>
<h3 name="The_2D_Rendering_Context"> The 2D Rendering Context </h3>
<h4 name="A_Simple_Example"> A Simple Example </h4>
<p>To start off, here's a simple example that draws two intersecting
rectangles, one of which has alpha transparency:
</p><p><img align="right" alt="Example 1." src="File:en/Media_Gallery/Canvas_ex1.png">
</p>
<pre class="eval">&lt;html&gt;
 &lt;head&gt;
  &lt;script type="application/x-javascript"&gt;
function init() {
 var canvas = document.getElementById("canvas");
 var ctx = canvas.getContext("2d");

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

 ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
 ctx.fillRect (30, 30, 50, 50);
}
  &lt;/script&gt;
 &lt;/head&gt;
 &lt;body onload="init()"&gt;
   &lt;canvas id="canvas" width="300" height="300"&gt;&lt;/canvas&gt;
 &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The <code>draw</code> function gets the <code>canvas</code> element, then
obtains the <code>2d</code> context.  The <code>ctx</code> object can then be
used to actually render to the canvas.  The example simply fills two
rectangles, by setting fillStyle to two different colors using CSS
color specifications and calling <code>fillRect</code>.  The second
fillStyle uses <code>rgba()</code> to specify an alpha value along with
the color.
</p><p>The <code>fillRect</code>, <code>strokeRect</code>, and <code>clearRect</code> calls render a filled, outlined, or clear rectangle.  To render more complex
shapes, paths are used.
</p>
<h4 name="Using_Paths"> Using Paths </h4>
<p>The <code>beginPath</code> function starts a new path, and
<code>moveTo</code>, <code>lineTo</code>, <code>arcTo</code>, <code>arc</code>, and similar methods are used to add segments to the path.  The path can be
closed using <code>closePath</code>.  Once you have a path is created, you
can use <code>fill</code> or <code>stroke</code> to render the path
to the canvas.
</p><p><img align="right" alt="Example 2." src="File:en/Media_Gallery/Canvas_ex2.png">
</p>
<pre class="eval">&lt;html&gt;
 &lt;head&gt;
  &lt;script type="application/x-javascript"&gt;
function draw() {
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");

  ctx.fillStyle = "red";

  ctx.beginPath();
  ctx.moveTo(30, 30);
  ctx.lineTo(150, 150);
  ctx.quadraticCurveTo(60, 70, 70, 150);
  ctx.lineTo(30, 30);
  ctx.fill();
}
   &lt;/script&gt;
 &lt;/head&gt;
 &lt;body onload="draw()"&gt;
   &lt;canvas id="canvas" width="300" height="300"&gt;&lt;/canvas&gt;
 &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Calling <code>fill()</code> or <code>stroke()</code> causes the current path
to be used.  To be filled or stroked again, the path must be recreated.
</p>
<h4 name="Graphics_State"> Graphics State </h4>
<p>Attributes of the context such as <code>fillStyle</code>,
<code>strokeStyle</code>, <code>lineWidth</code>, and <code>lineJoin</code> are
part of the current <i>graphics state</i>.  The context provides two
methods, <code>save()</code> and <code>restore()</code>, that can be used to
move the current state to and from the state stack.
</p>
<h4 name="A_More_Complicated_Example"> A More Complicated Example </h4>
<p>Here's a little more complicated example, that uses paths, state, and
also introduces the current transformation matrix.  The context
methods <code>translate()</code>, <code>scale()</code>, and <code>rotate()</code>
all transform the current matrix.  All rendered points are first
transformed by this matrix.
</p><p><img align="right" alt="Example 3." src="File:en/Media_Gallery/Canvas_ex3.png">
</p>
<pre> &lt;html&gt;
  &lt;head&gt;
   &lt;script type="application/x-javascript"&gt;
 function drawBowtie(ctx, fillStyle) {
 
   ctx.fillStyle = "rgba(200,200,200,0.3)";
   ctx.fillRect(-30, -30, 60, 60);
 
   ctx.fillStyle = fillStyle;
   ctx.globalAlpha = 1.0;
   ctx.beginPath();
   ctx.moveTo(25, 25);
   ctx.lineTo(-25, -25);
   ctx.lineTo(25, -25);
   ctx.lineTo(-25, 25);
   ctx.closePath();
   ctx.fill();
 }
 
 function dot(ctx) {
   ctx.save();
   ctx.fillStyle = "black";
   ctx.fillRect(-2, -2, 4, 4);
   ctx.restore();
 }
 
 function draw() {
   var canvas = document.getElementById("canvas");
   var ctx = canvas.getContext("2d");

   // note that all other translates are relative to this
   // one
   ctx.translate(45, 45);

   ctx.save();
   //ctx.translate(0, 0); // unnecessary
   drawBowtie(ctx, "red");
   dot(ctx);
   ctx.restore();
 
   ctx.save();
   ctx.translate(85, 0);
   ctx.rotate(45 * Math.PI / 180);
   drawBowtie(ctx, "green");
   dot(ctx);
   ctx.restore();
 
   ctx.save();
   ctx.translate(0, 85);
   ctx.rotate(135 * Math.PI / 180);
   drawBowtie(ctx, "blue");
   dot(ctx);
   ctx.restore();
 
   ctx.save();
   ctx.translate(85, 85);
   ctx.rotate(90 * Math.PI / 180);
   drawBowtie(ctx, "yellow");
   dot(ctx);
   ctx.restore();
 }
    &lt;/script&gt;
  &lt;/head&gt;
  &lt;body onload="draw()"&gt;
    &lt;canvas id="canvas" width="300" height="300"&gt;&lt;/canvas&gt;
  &lt;/body&gt;
 &lt;/html&gt;
</pre>
<p>This defines two methods, <code>drawBowtie</code> and <code>dot</code>, that
are called 4 times.  Before each call, <code>translate()</code> and
<code>rotate()</code> are used to set up the current transformation
matrix, which in turn positions the dot and the bowtie.  <code>dot</code>
renders a small black square centered at <code>(0, 0)</code>.  That dot is
moved around by the transformation matrix.  <code>drawBowtie</code>
renders a simple bowtie path using the passed-in fill style.
</p><p>As matrix operations are cumulative, <code>save()</code> and
<code>restore()</code> are used around each set of calls to restore the
original canvas state.  One thing to watch out for is that rotation
always occurs around the current origin; thus a <code>translate()
rotate() translate()</code> sequence will yield different results than a
<code>translate() translate() rotate()</code> series of calls.
</p>
Revert to this revision