溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

HTML5 Canvas有什么用

發(fā)布時(shí)間:2021-10-11 15:18:45 來源:億速云 閱讀:133 作者:小新 欄目:web開發(fā)

這篇文章給大家分享的是有關(guān)HTML5 Canvas有什么用的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

<canvas>是一個(gè)新的HTML元素,這個(gè)元素可以被Script語言(通常是JavaScript)用來繪制圖形。例如可以用它來畫圖、合成圖象、或做簡(jiǎn)單的(和不那么簡(jiǎn)單的)動(dòng)畫。右面的圖象展示了一些<canvas>的應(yīng)用示例,我們將會(huì)在此教程中看到他們的實(shí)現(xiàn)。

<canvas>最先在蘋果公司(Apple)的Mac OS X Dashboard上被引入,而后被應(yīng)用于Safari?;贕ecko1.8的瀏覽器,例如Firefox 1.5,也支持這個(gè)新元素。元素<canvas>是WhatWG Web applications 1.0也就是大家都知道的HTML 5標(biāo)準(zhǔn)規(guī)范的一部分。

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

開始使用之前
用元素<canvas>并不難,只要你具有HTML和 JavaScript的基礎(chǔ)知識(shí)。

如上所述,并不是所有現(xiàn)代瀏覽器都支持<canvas>元素,所以你需要 Firefox 1.5或更新版本、或者其他基于Gecko的瀏覽器例如Opera 9、或者最近版本的Safari才能看到所有示例的動(dòng)作。

<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.它只有兩個(gè)屬性,widthheight,兩個(gè)都是可選的,并且都可以 DOM 或者 CSS 來設(shè)置。 When no width and height attributes are specified, the canvas will initially be 300 pixels wide and 150 pixels high.如果不指定width 和 height,默認(rèn)的是寬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 來調(diào)整canvas的大小,但渲染圖像會(huì)縮放來適應(yīng)布局的(如果你發(fā)現(xiàn)渲染結(jié)果看上去變形了,不必一味依賴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>專享的,就像標(biāo)準(zhǔn)的HTLM標(biāo)簽一樣,任何一個(gè)HTML元素都可以指定其 id 值。一般,為元素指定 id 是個(gè)不錯(cuò)的主意,這樣使得在腳本中應(yīng)用更加方便。

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>元素可以像普通圖片一樣指定其樣式(邊距,邊框,背景等等)。然而這些樣式并不會(huì)對(duì)canvas實(shí)際生成的圖像產(chǎn)生什么影響。下面我們會(huì)看到如何應(yīng)用樣式。如果不指定樣式,canvas默認(rèn)是全透明的。

替用內(nèi)容

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.

因?yàn)?<canvas> 相對(duì)較新,有些瀏覽器并沒實(shí)現(xiàn),如Firefox 1.0 和 Internet Explorer,所以我們需要為那些不支持canvas的瀏覽器提供替用顯示內(nèi)容。

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元素內(nèi)插入替用內(nèi)容即可。不支持canvas的瀏覽器會(huì)忽略canvas元素而直接渲染替用內(nèi)容,而支持的瀏覽器則會(huì)正常地渲染canvas。例如,我們可以把一些文字或圖片填入canvas內(nèi),作為替用內(nèi)容:

<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>
結(jié)束標(biāo)簽 </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>的實(shí)現(xiàn)跟<img>很相似,它并不沒有結(jié)束標(biāo)簽。然而,為了使 <canvas> 能在web的世界里廣泛適用,需要給替用內(nèi)容提供一個(gè)容身之所,因此,在Mozilla的實(shí)現(xiàn)里結(jié)束標(biāo)簽(</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.

如果沒有替用內(nèi)容,<canvas id="foo" ...></canvas> 對(duì) Safari 和 Mozilla 是完全兼容的&mdash;&mdash; Safari 會(huì)簡(jiǎn)單地忽略結(jié)束標(biāo)簽。

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

如果有替用內(nèi)容,那么可以用一些 CSS 技巧來為并且僅為 Safari 隱藏替用內(nèi)容,因?yàn)槟切┨嬗脙?nèi)容是需要在 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> 創(chuàng)建的固定尺寸的繪圖畫面開放了一個(gè)或多個(gè)渲染上下文(rendering context),我們可以通過它們來控制要顯示的內(nèi)容。我們專注于2D 渲染上,這也是目前唯一的選擇,可能在將來會(huì)添加基于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 元素對(duì)象的 getContext 方法來獲取,同時(shí)得到的還有一些畫圖用的函數(shù)。getContext() 接受一個(gè)用于描述其類型的值作為參數(shù)。

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 對(duì)象的 DOM 節(jié)點(diǎn)。然后通過其 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:

除了在那些不支持  的瀏覽器上顯示替用內(nèi)容,還可以通過腳本的方式來檢查瀏覽器是否支持 canvas 。方法很簡(jiǎn)單,判斷 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.

我們會(huì)用下面這個(gè)最簡(jiǎn)化的代碼模板來(后續(xù)的示例需要用到)作為開始,你可以 下載文件 到本地備用。

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

細(xì)心的你會(huì)發(fā)現(xiàn)我準(zhǔn)備了一個(gè)名為 draw 的函數(shù),它會(huì)在頁面裝載完畢之后執(zhí)行一次(通過設(shè)置 body 標(biāo)簽的 onload 屬性),它當(dāng)然也可以在 setTimeout,setInterval,或者其他事件處理函數(shù)中被調(diào)用。

一個(gè)簡(jiǎn)單的例子

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.

作為開始,來一個(gè)簡(jiǎn)單的吧&mdash;&mdash;繪制兩個(gè)交錯(cuò)的矩形,其中一個(gè)是有alpha透明效果。我們會(huì)在后面的示例中詳細(xì)的讓你了解它是如何運(yùn)作的。

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

感謝各位的閱讀!關(guān)于“HTML5 Canvas有什么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI