濮阳杆衣贸易有限公司

主頁 > 知識庫 > HTML5 canvas 基本語法

HTML5 canvas 基本語法

熱門標(biāo)簽:平頂山電子地圖標(biāo)注怎么修改 地圖標(biāo)注自己去過的地方 會聲會影怎樣做地圖標(biāo)注效果 洛陽市伊川縣地圖標(biāo)注中心官網(wǎng) 電銷機器人視頻 標(biāo)準(zhǔn)智能外呼系統(tǒng) 江蘇高頻外呼系統(tǒng)線路 高德地圖標(biāo)注錯誤怎么修改 搜狗星級酒店地圖標(biāo)注

HTML 5 canvas —— 基本語法

簡述

5 規(guī)范引進了很多新特性,其中最令人期待的之一就是 元素。HTML 5 提供了通過 JavaScript 繪制圖形的方法,此方法使用簡單但功能強大。每一個 元素都有一個"上下文( context )" (想象成繪圖板上的一頁),在其中可以繪制任意圖形。瀏覽器支持多個 canvas 上下文,并通過不同的 提供圖形繪制功能。 5 規(guī)范引進了很多新特性,其中最令人期待的之一就是 元素。 5 提供了通過 JavaScript 繪制圖形的方法,此方法使用簡單但功能強大。每一個 元素都有一個"上下文( context )" (想象成繪圖板上的一頁),在其中可以繪制任意圖形。瀏覽器支持多個 canvas 上下文,并通過不同的 提供圖形繪制功能。

大部分的瀏覽器都支持 2D canvas 上下文——包括 Opera, Firefox, Konqueror 和 Safari。而且某些版本的 Opera 還支持 3D canvas ,F(xiàn)irefox 也可以通過插件形式支持 3D canvas :

  • 下載支持 3D canvas, HTML video 和 File I/O 的 Opera
  • 關(guān)于 Opera 3D canvas 上下文的文章
  • 關(guān)于 Firefox 3D canvas
    上下文的文章

本文介紹 2D canvas
基礎(chǔ)以及如何使用基本 canvas 函數(shù),如線條、形狀、圖像和文字等。為了理解此文章,你最好了解 JavaScript 基礎(chǔ)知識。

可以點擊此處批量下載本文實例代碼

canvas 基礎(chǔ)

創(chuàng)建 canvas 的方法很簡單,只需要在 HTML 頁面中添加 <canvas> 元素:

<canvas id="myCanvas" width="300" height="150">
Fallback content, in case the browser does not support Canvas.
</canvas>

為了能在 JavaScript 中引用元素,最好給元素設(shè)置 ID ;也需要給 canvas 設(shè)定高度和寬度。

創(chuàng)建好了畫布后,讓我們來準(zhǔn)備畫筆。要在畫布中繪制圖形需要使用 JavaScript 。首先通過 getElementById 函數(shù)找到 canvas
元素,然后初始化上下文。之后可以使用上下文 API 繪制各種圖形。下面的腳本在 canvas 中繪制一個矩形 (點擊此處查看效果):

// Get a reference to the element.
var elem = document.getElementById('myCanvas');

// Always check for properties 和 methods, to make sure your code doesn't break 
// in other browsers.
if (elem && elem.getContext) {
  // Get the 2d context.
  // Remember: you can only initialize one context per element.
  var context = elem.getContext('2d');
  if (context) {
    // You are done! Now you can draw your first rectangle.
    // You only need to provide the (x,y) coordinates, followed by the width and 
    // height dimensions.
    context.fillRect(0, 0, 150, 100);
  }
}

可以把上面代碼放置在文檔 head 部分中,或者放在外部文件中。

2D context API

介紹了如何創(chuàng)建 canvas 后,讓我們來看看 2D canvas API,看看能用這些函數(shù)做些什么。

基本線條

上面的例子中展示了繪制矩形是多么簡單。

通過 fillStylestrokeStyle 屬性可以輕松的設(shè)置矩形的填充和線條。顏色值使用方法和 十六進制數(shù)、()、() 和 ()( 若瀏覽器支持,如 Opera10 和 Firefox 3)。十六進制數(shù)、()、() 和 ()( 若瀏覽器支持,如 Opera10 和 Firefox 3)。

通過 fillRect 可以繪制帶填充的矩形。使用 strokeRect 可以繪制只有邊框沒有填充的矩形。如果想清除部分 canvas 可以使用 clearRect。上述三個方法的參數(shù)相同:x, y, width, height。前兩個參數(shù)設(shè)定 (x,y) 坐標(biāo),后兩個參數(shù)設(shè)置矩形的高度和寬度。

可以使用 lineWidth 屬性改變線條粗細(xì)。讓我們看看使用了fillRect,
strokeRect clearRect 和其他的例子:

context.fillStyle   = '#00f'; // blue
context.strokeStyle = '#f00'; // red
context.lineWidth   = 4;

// Draw some rectangles.
context.fillRect  (0,   0, 150, 50);
context.strokeRect(0,  60, 150, 50);
context.clearRect (30, 25,  90, 60);
context.strokeRect(30, 25,  90, 60);

此例子效果圖見圖1.


圖 1: fillRect, strokeRect 和
clearRect效果圖

路徑

通過 canvas 路徑(path)可以繪制任意形狀??梢韵壤L制輪廓,然后繪制邊框和填充。創(chuàng)建自定義形狀很簡單,使用 beginPath()開始繪制,然后使用直線、曲線和其他圖形繪制你的圖形。繪制完畢后調(diào)用 fillstroke 即可添加填充或者設(shè)置邊框。調(diào)用 closePath() 結(jié)束自定義圖形繪制。

下面是一個繪制三角形的例子:

// Set the style properties.
context.fillStyle   = '#00f';
context.strokeStyle = '#f00';
context.lineWidth   = 4;

context.beginPath();
// Start from the top-left point.
context.moveTo(10, 10); // give the (x,y) coordinates
context.lineTo(100, 10);
context.lineTo(10, 100);
context.lineTo(10, 10);

// Done! Now fill the shape, 和 draw the stroke.
// Note: your shape will not be visible until you call any of the two methods.
context.fill();
context.stroke();
context.closePath();

其效果圖見圖2.


圖 2: 三角形

另一個較負(fù)責(zé)的例子中使用了直線、曲線和圓弧。

插入圖像

drawImage 方法允許在 canvas 中插入其他圖像
( imgcanvas 元素) 。在 Opera 中可以再 canvas 中繪制 SVG 圖形。此方法比較復(fù)雜,可以有3個、5個或9個參數(shù):

  • 3個參數(shù):最基本的 drawImage 使用方法。一個參數(shù)指定圖像位置,另兩個參數(shù)設(shè)置圖像在 canvas中的位置。
  • 5個參數(shù):中級的 drawImage 使用方法,包括上面所述3個參數(shù),加兩個參數(shù)指明插入圖像寬度和高度 (如果你想改變圖像大小)。
  • 9個參數(shù):最復(fù)雜 drawImage 雜使用方法,包含上述5個參數(shù)外,另外4個參數(shù)設(shè)置源圖像中的位置和高度寬度。這些參數(shù)允許你在顯示圖像前動態(tài)裁剪源圖像。

下面是上述三個使用方法的例子:

// Three arguments: the element, destination (x,y) coordinates.
context.drawImage(img_elem, dx, dy);

// Five arguments: the element, destination (x,y) coordinates, and destination 
// width and height (if you want to resize the source image).
context.drawImage(img_elem, dx, dy, dw, dh);

// Nine arguments: the element, source (x,y) coordinates, source width and 
// height (for cropping), destination (x,y) coordinates, and destination width 
// and height (resize).
context.drawImage(img_elem, sx, sy, sw, sh, dx, dy, dw, dh);

其效果見圖3.


圖 3: drawImage 效果圖。

像素級操作

2D Context API 提供了三個方法用于像素級操作:createImageData, getImageData, 和
putImageData。

ImageData對象保存了圖像像素值。每個對象有三個屬性: width, height
datadata 屬性類型為CanvasPixelArray,用于儲存width*height*4個像素值。每一個像素有RGB值和透明度alpha值(其值為 0 至
255,包括alpha在內(nèi)!)。像素的順序從左至右,從上到下,按行存儲。

為了更好的理解其原理,讓我們來看一個例子——繪制紅色矩形

// Create an ImageData object.
var imgd = context.createImageData(50,50);
var pix = imgd.data;

// Loop over each pixel 和 set a transparent red.
for (var i = 0; n = pix.length, i < n; i += 4) {
  pix[i  ] = 255; // red channel
  pix[i+3] = 127; // alpha channel
}

// Draw the ImageData object at the given (x,y) coordinates.
context.putImageData(imgd, 0,0);

注意: 不是所有瀏覽器都實現(xiàn)了 createImageData。在支持的瀏覽器中,需要通過 getImageData 方法獲取 ImageData 對象。請參考示例代碼。

通過 ImageData 可以完成很多功能。如可以實現(xiàn)圖像濾鏡,或可以實現(xiàn)數(shù)學(xué)可視化 (如分形和其他特效)。下面特效實現(xiàn)了簡單的顏色反轉(zhuǎn)濾鏡:

// Get the CanvasPixelArray from the given coordinates and dimensions.
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;

// Loop over each pixel and invert the color.
for (var i = 0, n = pix.length; i < n; i += 4) {
  pix[i  ] = 255 - pix[i  ]; // red
  pix[i+1] = 255 - pix[i+1]; // green
  pix[i+2] = 255 - pix[i+2]; // blue
  // i+3 is alpha (the fourth element)
}

// Draw the ImageData at the given (x,y) coordinates.
context.putImageData(imgd, x, y);

圖 4 顯示了使用此濾鏡后的 Opera
圖像 (圖 3是原圖)。


圖 4: 顏色反轉(zhuǎn)濾鏡

文字

雖然最近的 WebKit 版本和 Firefox 3.1 nightly build 才開始支持 Text API ,為了保證文章完整性我決定仍在這里介紹文字 API 。

context 對象可以設(shè)置以下 text 屬性:

  • font:文字字體,同屬性 屬性
  • textAlign:文字水平對齊方式。可取屬性值: start, end, left,
    right, center。默認(rèn)值:
    start.
  • textBaseline:文字豎直對齊方式??扇傩灾担?code>top, hanging, middle,
    alphabetic, ideographic, bottom。默認(rèn)值:alphabetic.

有兩個方法可以繪制文字: fillTextstrokeText。第一個繪制帶 fillStyle 填充的文字,后者繪制只有 strokeStyle 邊框的文字。兩者的參數(shù)相同:要繪制的文字和文字的位置(x,y) 坐標(biāo)。還有一個可選選項——最大寬度。如果需要的話,瀏覽器會縮減文字以讓它適應(yīng)指定寬度。

文字對齊屬性影響文字與設(shè)置的
(x,y) 坐標(biāo)的相對位置。

下面是一個在 canvas 中繪制"hello world" 文字的例子

context.fillStyle    = '#00f';
context.font         = 'italic 30px sans-serif';
context.textBaseline = 'top';
context.fillText  ('Hello world!', 0, 0);
context.font         = 'bold 30px sans-serif';
context.strokeText('Hello world!', 0, 50);

圖 5 是其效果圖。


圖 5: 文字效果

陰影

目前只有 Konqueror 和 Firefox 3.1 nightly build 支持 Shadows API 。API 的屬性為:

  • shadowColor:陰影顏色。其值和 CSS 顏色值一致。
  • shadowBlur:設(shè)置陰影模糊程度。此值越大,陰影越模糊。其效果和 Photoshop 的高斯模糊濾鏡相同。
  • shadowOffsetXshadowOffsetY:陰影的 x 和 y 偏移量,單位是像素。

下面是 canvas 陰影的例子:

context.shadowOffsetX = 5;
context.shadowOffsetY = 5;
context.shadowBlur    = 4;
context.shadowColor   = 'rgba(255, 0, 0, 0.5)';
context.fillStyle     = '#00f';
context.fillRect(20, 20, 150, 100);

其效果見圖 6。


圖 6: canvas 陰影效果——藍(lán)色矩形,紅色陰影

顏色漸變

除了 CSS 顏色, fillStylestrokeStyle 屬性可以設(shè)置為 CanvasGradient 對象。——通過 CanvasGradient可以為線條和填充使用顏色漸變。

欲創(chuàng)建 CanvasGradient 對象,可以使用兩個方法:createLinearGradientcreateRadialGradient。前者創(chuàng)建線性顏色漸變,后者創(chuàng)建圓形顏色漸變。

創(chuàng)建顏色漸變對象后,可以使用對象的 addColorStop 方法添加顏色中間值。

下面的代碼演示了顏色漸變使用方法:

// You need to provide the source 和 destination (x,y) coordinates 
// for the gradient (from where it starts 和 where it ends).
var gradient1 = context.createLinearGradient(sx, sy, dx, dy);

// Now you can add colors in your gradient.
// The first argument tells the position for the color in your gradient. The 
// accepted value range is from 0 (gradient start) to 1 (gradient end).
// The second argument tells the color you want, using the CSS color format.
gradient1.addColorStop(0,   '#f00'); // red
gradient1.addColorStop(0.5, '#ff0'); // yellow
gradient1.addColorStop(1,   '#00f'); // blue

// For the radial gradient you also need to provide source
// 和 destination circle radius.
// The (x,y) coordinates define the circle center points (start 和 
// destination).
var gradient2 = context.createRadialGradient(sx, sy, sr, dx, dy, dr);

// Adding colors to a radial gradient is the same as adding colors to linear 
// gradients.

我也準(zhǔn)備了一個更復(fù)雜的例子,使用了線性顏色漸變、陰影和文字。其效果見圖 7。


圖 7: 使用線性顏色漸變的例子

canvas 演示

如果你想知道使用 Canvas可以做些什么,可以參看以下的工程:

  • Opera Widget:
    • SimAquarium
    • Artist's
      Sketchbook
    • Spirograph
  • 在線工程和演示
    • Newton polynomial
    • Canvascape - "3D Walker"
    • Paint.Web - painting
      demo, open-source
    • Star-field
      flight
    • Interactive blob

小節(jié)

Canvas 是 HTML 5最讓人期待的特性之一,目前已獲得大部分 Web 瀏覽器支持。Canvas 可以幫助創(chuàng)建游戲、增強圖形用戶界面。2D context
API 提供大量圖形繪制功能——我希望通過本文你了解了 canvas 使用,并且你有興趣了解更多!

標(biāo)簽:阿克蘇 常德 鄂爾多斯 蚌埠 廣西 果洛 廣東 松原

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《HTML5 canvas 基本語法》,本文關(guān)鍵詞  HTML5,canvas,基本,語法,HTML5,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《HTML5 canvas 基本語法》相關(guān)的同類信息!
  • 本頁收集關(guān)于HTML5 canvas 基本語法的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    虹口区| 南江县| 贺州市| 延安市| 中西区| 自治县| 永丰县| 秦皇岛市| 垫江县| 公主岭市| 米林县| 哈尔滨市| 白河县| 交口县| 鱼台县| 莎车县| 新巴尔虎左旗| 宜君县| 道真| 上虞市| 达州市| 梁平县| 林周县| 定边县| 崇左市| 唐河县| 萍乡市| 洮南市| 太仆寺旗| 海晏县| 南靖县| 乌什县| 莲花县| 寿阳县| 秭归县| 安康市| 辽宁省| 太康县| 安陆市| 仁怀市| 东阳市|