DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> HTML基礎知識 >> HTML和Xhtml >> Canvas教程(2):基本用法
Canvas教程(2):基本用法
編輯:HTML和Xhtml     

網頁制作poluoluo文章簡介:canvas是一個新的HTML元素,這個元素可以被Script語言(通常是JavaScript)用來繪制圖形。例如可以用它來畫圖、合成圖象、或做簡單的(和不那麼簡單的)動畫。右面的圖象展示了一些canvas的應用示例,我們將會在此教程中看到他們的實現。 canvas最先在蘋果公司(Apple)的Mac

<canvas>是一個新的HTML元素,這個元素可以被Script語言(通常是JavaScript)用來繪制圖形。例如可以用它來畫圖、合成圖象、或做簡單的(和不那麼簡單的)動畫。右面的圖象展示了一些<canvas>的應用示例,我們將會在此教程中看到他們的實現。

<canvas>最先在蘋果公司(Apple)的Mac OS X Dashboard上被引入,而後被應用於Safari。基於Gecko1.8的浏覽器,例如Firefox 1.5,也支持這個新元素。元素<canvas>是WhatWG Web applications 1.0也就是大家都知道的HTML 5標准規范的一部分。

在本教程中,我將試著講述如何在你自己的網頁中使用<canvas>元素。提供的示例應該會給你些清晰概念,即用<canvas>能做些什麼的。這些示例也可作為你應用<canvas>的起點。

開始使用之前
用元素<canvas>並不難,只要你具有HTML和 JavaScript的基礎知識。

如上所述,並不是所有現代浏覽器都支持<canvas>元素,所以你需要 Firefox 1.5或更新版本、或者其他基於Gecko的浏覽器例如Opera 9、或者最近版本的Safari才能看到所有示例的動作。

<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>,唯一不同就是它不含 src 和 alt 屬性。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>

結束標簽 </canvas> 是必須的

In the Apple Safari implementation, <canvas> is an element implemented in much the same way <img> is; it does not have an end tag. However, for <canvas> to have widespread use on the web, some facility for fallback content must be provided. Therefore, Mozilla's implementation requires an end tag (</canvas>).

在Apple Safari裡,<canvas>的實現跟<img>很相似,它並不沒有結束標簽。然而,為了使 <canvas> 能在web的世界裡廣泛適用,需要給替用內容提供一個容身之所,因此,在Mozilla的實現裡結束標簽(</canvas>)是必須的。

If fallback content is not needed, a simple <canvas id="foo" ...></canvas> will be fully compatible with both Safari and Mozilla -- Safari will simply ignore the end tag.

如果沒有替用內容,<canvas id="foo" ...></canvas> 對 Safari 和 Mozilla 是完全兼容的—— Safari 會簡單地忽略結束標簽。

If fallback content is desired, some CSS tricks must be employed to mask the fallback content from Safari (which should render just the canvas), and also to mask the CSS tricks themselves from IE (which should render the fallback content).

如果有替用內容,那麼可以用一些 CSS 技巧來為並且僅為 Safari 隱藏替用內容,因為那些替用內容是需要在 IE 裡顯示但不需要在 Safari 裡顯示。

渲染上下文(Rendering Context)

<canvas> creates a fixed size drawing surface that exposes one or more rendering contexts, which are used to create and manipulate the content shown. We'll focus on the 2D rendering context, which is the only currently defined rendering context. In the future, other contexts may provide different types of rendering; for example, it is likely that a 3D context based on OpenGL ES will be added.

<canvas> 創建的固定尺寸的繪圖畫面開放了一個或多個渲染上下文(rendering context),我們可以通過它們來控制要顯示的內容。我們專注於2D 渲染上,這也是目前唯一的選擇,可能在將來會添加基於OpenGL ES 的 3D 上下文。

The <canvas> is initially blank, and to display something a script first needs to access the rendering context and draw on it. The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions. getContext() takes one parameter, the type of context.

<canvas> 初始化是空白的,要在上面用腳本畫圖首先需要其渲染上下文(rendering context),它可以通過 canvas 元素對象的 getContext 方法來獲取,同時得到的還有一些畫圖用的函數。getContext() 接受一個用於描述其類型的值作為參數。

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

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

上面第一行通過 getElementById 方法取得 canvas 對象的 DOM 節點。然後通過其 getContext 方法取得其畫圖操作上下文。

檢查浏覽器的支持

The fallback content is displayed in browsers which do not support <canvas>; scripts can also check for support when they execute. This can easily be done by testing for the getContext method. Our code snippet from above becomes something like this:

除了在那些不支持  的浏覽器上顯示替用內容,還可以通過腳本的方式來檢查浏覽器是否支持 canvas 。方法很簡單,判斷 getContext 是否存在即可。

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

代碼模板

Here is a minimalistic template, which we'll be using as a starting point for later examples. You can download this file to work with on your system.

我們會用下面這個最簡化的代碼模板來(後續的示例需要用到)作為開始,你可以 下載文件 到本地備用。

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

細心的你會發現我准備了一個名為 draw 的函數,它會在頁面裝載完畢之後執行一次(通過設置 body 標簽的 onload 屬性),它當然也可以在 setTimeout,setInterval,或者其他事件處理函數中被調用。

一個簡單的例子

To start off, here's a simple example that draws two intersecting rectangles, one of which has alpha transparency. We'll explore how this works in more detail in later examples.

作為開始,來一個簡單的吧——繪制兩個交錯的矩形,其中一個是有alpha透明效果。我們會在後面的示例中詳細的讓你了解它是如何運作的。

<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"></canvas>
 </body>
</html>

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved