Basic usage

  • 版本网址缩略名: Canvas_tutorial/Basic_usage
  • 版本标题: Basic usage
  • 版本 id: 37847
  • 创建于:
  • 创建者: Xemacs
  • 是否是当前版本?
  • 评论 /* 要素 <code><canvas></code> */

修订内容

要素 <canvas>

Let's start this tutorial by looking at the <canvas> element itself. 让我们通过观看<canvas>这个元素开始这个教程。

<canvas id="tutorial" width="150" height="150"></canvas>

This looks a lot like the <img> element, the only difference is that it doesn't have the src and alt attributes. The <canvas> element has only two attributes - width and height. These are both optional and can also be set using DOM properties or CSS rules. When no width and height attributes are specified, the canvas will initially be 300 pixels wide and 150 pixels high.
The id attribute isn't specific to the <canvas> element but is one of default HTML attributes which can be applied to (almost) every HTML element (like class for instance). It's always a good idea to supply an id because this makes it much easier to identify it in our script.

The <canvas> element can be styled just like any normal image (margin, border, background, etc). These rules however don't affect the actual drawing on the canvas. We'll see how this is done later in this tutorial. When no styling rules are applied to the canvas it will initially be fully transparent.

Fallback content

Because the <canvas> element has only just been introduced and isn't implemented in many browsers, including Firefox 1.0 and Internet Explorer, we need a means of providing fallback content when a browser doesn't support the element.

Luckily this is very straightforward: we just provide alternative content inside the canvas element. Browsers who don't support it will ignore the element completely and render the fallback content, others will just render the canvas normally.
For instance we could provide a text description of the canvas content or provide a static image of the dynamically rendered content. This can look something like this:

<canvas id="stockGraph" width="150" height="150">
  current stock price: $3.15 +0.15
</canvas>

<canvas id="clock" width="150" height="150">
  <img src="images/clock.png" width="150" height="150"/>
</canvas>

Note: Apple's implementation currently differs from the specification in that it doesn't recognize the closing </canvas> tag. This means that in Safari all fallback content will be shown. This can be solved by either using CSS or scripting to hide it.

getContext

If you make an HTML page and load it into Firefox you won't see anything in the area occupied by the <canvas> element. We need a means to get to it to start drawing and that's where getContext comes in. Every canvas element has a DOM method called getContext to access the drawing functions. getContext can only take one parameter and that's the type of drawing context. Currently there's only one context available and that's the 2d context. In the future we might see a 3d context but for now we'll have to stick to the 2d context.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

In the first line we retrieve the DOM node using the getElementById method. We can then access the drawing context using the getContext method.

Prevent execution in unsupported browsers

Just like the fallback content we need a way to prevent browsers who don't support canvas from executing our script. This can easily be done by testing for the getContext method. Our code snippet from above becomes something like this:

var canvas = document.getElementById('canvas');
if (canvas.getContext){
  var ctx = canvas.getContext('2d');
  // drawing code here
}

All drawing code should go inside the if statement, so that the browsers not supporting <canvas> don't try to execute it.

Putting it together

If we put everything together a simple HTML template becomes something like this. I'll be using this setup for all the examples we'll see later in this tutorial.

Template

Download this file

<html>
  <head>
    <title>Canvas tutorial</title>
    <script type="text/javascript">
      function draw(){
        var canvas = document.getElementById('tutorial');
        if (canvas.getContext){
          var ctx = canvas.getContext('2d');
        }
      }
    </script>
    <style type="text/css">
      canvas { border: 1px solid black; }
    </style>
  </head>
  <body onload="draw();">
    <canvas id="tutorial" width="150" height="150"></canvas>
  </body>
</html>

If you look at the script you'll see I've made a function called draw, which will get executed once the page finishes loading (via the onload attribute on the body tag). This function could also have been called from a setTimeout, setInterval, or any other event handler function just as long the page has been loaded first.

These are the basics. On the following pages we'll finally do some actual drawing.

{{template.PreviousNext("Canvas tutorial", "Canvas tutorial:Drawing shapes")}}

{{ wiki.languages( { "en": "en/Canvas_tutorial/Basic_usage", "fr": "fr/Tutoriel_canvas/Utilisation_de_base", "ja": "ja/Canvas_tutorial/Basic_usage", "pl": "pl/Przewodnik_po_canvas/Proste_zastosowanie" } ) }}

修订版来源

<p>
</p>
<h2 name=".E8.A6.81.E7.B4.A0_.3Ccanvas.3E"> 要素 <code>&lt;canvas&gt;</code> </h2>
<p>Let's start this tutorial by looking at the <code>&lt;canvas&gt;</code> element itself. 
让我们通过观看<code>&lt;canvas&gt;</code>这个元素开始这个教程。
</p>
<pre class="eval">&lt;canvas id="tutorial" width="150" height="150"&gt;&lt;/canvas&gt;
</pre>
<p>This looks a lot like the <code>&lt;img&gt;</code> element, the only difference is that it doesn't have the <code>src</code> and <code>alt</code> attributes. The <code>&lt;canvas&gt;</code> element has only two attributes - <b>width</b> and <b>height</b>. These are both optional and can also be set using <a href="cn/DOM">DOM</a> properties or <a href="cn/CSS">CSS</a> rules. When no width and height attributes are specified, the canvas will initially be <b>300 pixels</b> wide and <b>150 pixels</b> high.<br>
The <code>id</code> attribute isn't specific to the <code>&lt;canvas&gt;</code> element but is one of default HTML attributes which can be applied to (almost) every HTML element (like <code>class</code> for instance). It's always a good idea to supply an id because this makes it much easier to identify it in our script.
</p><p>The <code>&lt;canvas&gt;</code> element can be styled just like any normal image (margin, border, background, etc). These rules however don't affect the actual drawing on the canvas. We'll see how this is done later in this tutorial.
When no styling rules are applied to the canvas it will initially be fully transparent.
</p>
<h4 name="Fallback_content"> Fallback content </h4>
<p>Because the <code>&lt;canvas&gt;</code> element has only just been introduced and isn't implemented in many browsers, including Firefox 1.0 and Internet Explorer, we need a means of providing fallback content when a browser doesn't support the element.
</p><p>Luckily this is very straightforward: we just provide alternative content inside the canvas element. Browsers who don't support it will ignore the element completely and render the fallback content, others will just render the canvas normally.<br>
For instance we could provide a text description of the canvas content or provide a static image of the dynamically rendered content. This can look something like this:
</p>
<pre>&lt;canvas id="stockGraph" width="150" height="150"&gt;
  current stock price: $3.15 +0.15
&lt;/canvas&gt;

&lt;canvas id="clock" width="150" height="150"&gt;
  &lt;img src="images/clock.png" width="150" height="150"/&gt;
&lt;/canvas&gt;
</pre>
<p><b>Note</b>: Apple's implementation currently differs from the specification in that it doesn't recognize the closing <code>&lt;/canvas&gt;</code> tag. This means that in Safari all fallback content will be shown. This can be solved by either using CSS or scripting to hide it.
</p>
<h2 name="getContext"> getContext </h2>
<p>If you make an HTML page and load it into Firefox you won't see anything in the area occupied by the <code>&lt;canvas&gt;</code> element. We need a means to get to it to start drawing and that's where <b>getContext</b> comes in. Every canvas element has a DOM method called <code>getContext</code> to access the drawing functions. <code>getContext</code> can only take one parameter and that's the type of <i>drawing context</i>. Currently there's only one context available and that's the <b>2d context</b>. In the future we might see a 3d context but for now we'll have to stick to the 2d context.
</p>
<pre class="eval">var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
</pre>
<p>In the first line we retrieve the DOM node using the <a href="cn/DOM/document.getElementById">getElementById</a> method. We can then access the drawing context using the <code>getContext</code> method.
</p>
<h3 name="Prevent_execution_in_unsupported_browsers"> Prevent execution in unsupported browsers </h3>
<p>Just like the fallback content we need a way to prevent browsers who don't support canvas from executing our script. This can easily be done by testing for the getContext method. Our code snippet from above becomes something like this:
</p>
<pre class="eval">var canvas = document.getElementById('canvas');
if (canvas.getContext){
  var ctx = canvas.getContext('2d');
  // drawing code here
}
</pre>
<p>All drawing code should go inside the <code>if</code> statement, so that the browsers not supporting <code>&lt;canvas&gt;</code> don't try to execute it.
</p>
<h2 name="Putting_it_together"> Putting it together </h2>
<p>If we put everything together a simple HTML template becomes something like this. I'll be using this setup for all the examples we'll see later in this tutorial. 
</p>
<h4 name="Template"> Template </h4>
<p><a class="external" href="http://developer.mozilla.org/samples/canvas-tutorial/1_1_canvas_template.html">Download this file</a>
</p>
<pre>&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Canvas tutorial&lt;/title&gt;
    &lt;script type="text/javascript"&gt;
      function draw(){
        var canvas = document.getElementById('tutorial');
        if (canvas.getContext){
          var ctx = canvas.getContext('2d');
        }
      }
    &lt;/script&gt;
    &lt;style type="text/css"&gt;
      canvas { border: 1px solid black; }
    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body onload="draw();"&gt;
    &lt;canvas id="tutorial" width="150" height="150"&gt;&lt;/canvas&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>If you look at the script you'll see I've made a function called <code>draw</code>, which will get executed once the page finishes loading (via the <code>onload</code> attribute on the <code>body</code> tag). This function could also have been called from a <a href="cn/DOM/window.setTimeout">setTimeout</a>, <a href="cn/DOM/window.setInterval">setInterval</a>, or any other event handler function just as long the page has been loaded first.
</p><p>These are the basics. On the following pages we'll finally do some actual drawing.
</p><p>{{template.PreviousNext("Canvas tutorial", "Canvas tutorial:Drawing shapes")}}
</p>{{ wiki.languages( { "en": "en/Canvas_tutorial/Basic_usage", "fr": "fr/Tutoriel_canvas/Utilisation_de_base", "ja": "ja/Canvas_tutorial/Basic_usage", "pl": "pl/Przewodnik_po_canvas/Proste_zastosowanie" } ) }}
恢复到这个版本