Basic usage

  • 版本网址缩略名: Canvas_tutorial/Basic_usage
  • 版本标题: Basic usage
  • 版本 id: 37854
  • 创建于:
  • 创建者: leegorous
  • 是否是当前版本?
  • 评论 38 words added, 62 words removed

修订内容

 <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. <canvas>看起来很像<img>,唯一不同就是它不含 srcalt 属性。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.它只有两个属性,widthheight,两个都是可选的,并且都可以 DOM 或者 CSS 来设置。 When no width and height attributes are specified, the canvas will initially be 300 pixels wide and 150 pixels high.如果不指定width 和 height,默认的是宽300像素高150像素。The element can be sized arbitrarily by CSS, but during rendering the image is scaled to fit its layout size.   (If your  renderings seem distorted, try specifying your width and height attributes explicitly in the <canvas> attributes, and not with CSS.)虽然可以通过 CSS 来调整canvas的大小,但渲染图像会缩放来适应布局的(如果你发现渲染结果看上去变形了,不必一味依赖CSS,可以尝试显式指定canvas的width 和 height 属性值)。

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.
id  属性不是<canvas>专享的,就像标准的HTLM标签一样,任何一个HTML元素都可以指定其 id 值。一般,为元素指定 id 是个不错的主意,这样使得在脚本中应用更加方便。

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. <canvas>元素可以像普通图片一样指定其样式(边距,边框,背景等等)。然而这些样式并不会对canvas实际生成的图像产生什么影响。下面我们会看到如何应用样式。如果不指定样式,canvas默认是全透明的。

替用内容

Because the <canvas> element is still relatively new and isn't implemented in some browsers (such as Firefox 1.0 and Internet Explorer), we need a means of providing fallback content when a browser doesn't support the element.

因为<canvas>相对较新,有些浏览器并没实现,如Firefox 1.0 和 Internet Explorer,所以我们需要为那些不支持canvas的浏览器提供替用显示内容。

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元素内插入替用内容即可。不支持canvas的浏览器会忽略canvas元素而直接渲染替用内容,而支持的浏览器则会正常地渲染canvas。例如,我们可以把一些文字或图片填入canvas内,作为替用内容:

<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>

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.

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

{{ languages( { "en": "en/Canvas_tutorial/Basic_usage", "fr": "fr/Tutoriel_canvas/Utilisation_de_base", "it": "it/Canvas_tutorial/Utilizzo_di_base", "ja": "ja/Canvas_tutorial/Basic_usage", "pl": "pl/Przewodnik_po_canvas/Proste_zastosowanie", "ru": "ru/\u041e\u0431\u0443\u0447\u0435\u043d\u0438\u0435_canvas/\u041e\u0441\u043d\u043e\u0432\u044b" } ) }}

修订版来源

<p>
</p>
<h2 name=".E5.85.83.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. <br>
让我们从<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. &lt;canvas&gt;看起来很像&lt;img&gt;,唯一不同就是它不含<code> src</code> 和 <code>alt </code>属性。The <code>&lt;canvas&gt;</code> element has only two attributes - <strong>width</strong> and <strong>height</strong>. These are both optional and can also be set using <a href="/cn/DOM" title="cn/DOM">DOM</a> properties or <a href="/cn/CSS" title="cn/CSS">CSS</a> rules.它只有两个属性,<strong>width</strong> 和 <strong>height</strong>,两个都是可选的,并且都可以 <a href="/cn/DOM" title="cn/DOM">DOM</a> 或者 <a href="/cn/CSS" title="cn/CSS">CSS</a> 来设置。 When no width and height attributes are specified, the canvas will initially be <strong>300 pixels</strong> wide and <strong>150 pixels</strong> high.如果不指定width 和 height,默认的是<strong>宽300像素</strong>,<strong>高150像素</strong>。The element can be sized arbitrarily by <a href="../../../../en/CSS" rel="internal">CSS</a>, but during rendering the image is scaled to fit its layout size.   (If your  renderings seem distorted, try specifying your width and height attributes explicitly in the <code>&lt;canvas&gt;</code> attributes, and not with CSS.)虽然可以通过 <a href="../../../../en/CSS" rel="internal">CSS</a> 来调整canvas的大小,但渲染图像会缩放来适应布局的(如果你发现渲染结果看上去变形了,不必一味依赖CSS,可以尝试显式指定canvas的width 和 height 属性值)。</p>
<p>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.<br>
<code>id</code>  属性不是<code>&lt;canvas&gt;</code>专享的,就像标准的HTLM标签一样,任何一个HTML元素都可以指定其<code> id</code> 值。一般,为元素指定<code> id</code> 是个不错的主意,这样使得在脚本中应用更加方便。</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.<code> &lt;canvas&gt;</code>元素可以像普通图片一样指定其样式(边距,边框,背景等等)。然而这些样式并不会对canvas实际生成的图像产生什么影响。下面我们会看到如何应用样式。如果不指定样式,canvas默认是全透明的。</p>
<h4 name="Fallback_content">替用内容</h4>
<p>Because the <code>&lt;canvas&gt;</code> element is still relatively new and isn't implemented in some browsers (such as Firefox 1.0 and Internet Explorer), we need a means of providing fallback content when a browser doesn't support the element.</p>
<p>因为&lt;canvas&gt;相对较新,有些浏览器并没实现,如Firefox 1.0 和 Internet Explorer,所以我们需要为那些不支持canvas的浏览器提供替用显示内容。</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>
<p>我们只需要直接在canvas元素内插入替用内容即可。不支持canvas的浏览器会忽略canvas元素而直接渲染替用内容,而支持的浏览器则会正常地渲染canvas。例如,我们可以把一些文字或图片填入canvas内,作为替用内容:</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><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>{{ PreviousNext("Canvas tutorial", "Canvas tutorial:Drawing shapes") }}
</p>
<div class="noinclude">
</div>
{{ languages( { "en": "en/Canvas_tutorial/Basic_usage", "fr": "fr/Tutoriel_canvas/Utilisation_de_base", "it": "it/Canvas_tutorial/Utilizzo_di_base", "ja": "ja/Canvas_tutorial/Basic_usage", "pl": "pl/Przewodnik_po_canvas/Proste_zastosowanie", "ru": "ru/\u041e\u0431\u0443\u0447\u0435\u043d\u0438\u0435_canvas/\u041e\u0441\u043d\u043e\u0432\u044b" } ) }}
恢复到这个版本