- 簡述
- canvas 基礎
- 2D context API
- 基本線條
- 路徑
- 插入映像
- 像素級操作
- 文字
- 陰影
- 色彩坡形
- 小節
簡述
HTML 5 規範引進了很多新特性,其中最令人期待的之一就是 canvas 元素。HTML 5 canvas 提供了通過 JavaScript 繪製圖形的方法,此方法使用簡單但功能強大。每一個 canvas 元素都有一個"上下文( context )" (想象成繪圖板上的一頁),在其中可以繪製任意圖形。瀏覽器支援多個 canvas 上下文,並通過不同的 API 提供圖形繪製功能。
大部分的瀏覽器都支援 2D canvas 上下文——包括 Opera, Firefox, Konqueror 和 Safari。而且某些版本的 Opera 還支援 3D canvas ,Firefox 也可以通過外掛程式形式支援 3D canvas :
- 下載支援 3D canvas, HTML video 和 File I/O 的 Opera
- 關於 Opera 3D canvas 內容相關的文章
- 關於 Firefox 3D canvas
內容相關的文章
本文介紹 2D canvas
基礎以及如何使用基本 canvas 函數,如線條、形狀、映像和文字等。為了理解此文章,你最好瞭解 JavaScript 基礎知識。
可以點擊此處批量下載本文執行個體代碼
canvas 基礎
建立 canvas 的方法很簡單,只需要在 HTML 頁面中添加 <canvas> 元素:
<canvas id="myCanvas" width="300" height="150">Fallback content, in case the browser does not support Canvas.</canvas>
為了能在 JavaScript 中引用元素,最好給元素設定 ID ;也需要給 canvas 設定高度和寬度。
建立好了畫布後,讓我們來準備畫筆。要在畫布中繪製圖形需要使用 JavaScript 。首先通過 getElementById 函數找到 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
介紹了如何建立 canvas 後,讓我們來看看 2D canvas API,看看能用這些函數做些什麼。
基本線條
上面的例子中展示了繪製矩形是多麼簡單。
通過 fillStyle 和 strokeStyle 屬性可以輕鬆的設定矩形的填充和線條。顏色值使用方法和 CSS 一樣:十六進位數、rgb()、rgba() 和 hsla()( 若瀏覽器支援,如 Opera
10 和 Firefox 3)。
通過 fillRect 可以繪製帶填充的矩形。使用 strokeRect 可以繪製只有邊框沒有填充的矩形。如果想清除部分 canvas 可以使用 clearRect。上述三個方法的參數相同:x, y, width, height。前兩個參數設定 (x,y) 座標,後兩個參數設定矩形的高度和寬度。
可以使用 lineWidth 屬性改變線條寬度。讓我們看看使用了fillRect,
strokeRect clearRect 和其他的例子:
context.fillStyle = '#00f'; // bluecontext.strokeStyle = '#f00'; // redcontext.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)可以繪製任意形狀。可以先繪製輪廓,然後繪製邊框和填充。建立自訂形狀很簡單,使用 beginPath()開始繪製,然後使用直線、曲線和其他圖形繪製你的圖形。繪製完畢後調用 fill 和 stroke 即可添加填充或者設定邊框。調用 closePath() 結束自訂圖形繪製。
下面是一個繪製三角形的例子:
// 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) coordinatescontext.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: 三角形
另一個較負責的例子中使用了直線、曲線和圓弧。
插入映像
drawImage 方法允許在 canvas 中插入其他映像
( img 和 canvas 元素) 。在 Opera 中可以再 canvas 中繪製 SVG 圖形。此方法比較複雜,可以有3個、5個或9個參數:
- 3個參數:最基本的
drawImage 使用方法。一個參數指定映像位置,另兩個參數設定映像在 canvas中的位置。
- 5個參數:中級的
drawImage 使用方法,包括上面所述3個參數,加兩個參數指明插入映像寬度和高度 (如果你想改變映像大小)。
- 9個參數:最複雜
drawImage 雜使用方法,包含上述5個參數外,另外4個參數設定源映像中的位置和高度寬度。這些參數允許你在顯示映像前動態裁剪源映像。
下面是上述三個使用方法的例子:
// 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 和
data。data 屬性類型為CanvasPixelArray,用於儲存width*height*4個像素值。每一個像素有RGB值和透明度alpha值(其值為 0 至
255,包括alpha在內!)。像素的順序從左至右,從上到下,按行儲存。
為了更好的理解其原理,讓我們來看一個例子——繪製紅色矩形
// 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);
注意: 不是所有瀏覽器都實現了 createImageData。在支援的瀏覽器中,需要通過 getImageData 方法擷取 ImageData 對象。請參考範例程式碼。
通過 ImageData 可以完成很多功能。如可以實現映像濾鏡,或可以實現數學可視化 (如分形和其他特效)。下面特效實現了簡單的顏色反轉濾鏡:
// 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: 顏色反轉濾鏡
文字
雖然最近的 WebKit 版本和 Firefox 3.1 nightly build 才開始支援 Text API ,為了保證文章完整性我決定仍在這裡介紹文字 API 。
context 對象可以設定以下 text 屬性:
font:文字字型,同 CSS
font-family 屬性
textAlign:文字水平對齊。可取屬性值: start, end, left,
right, center。預設值:
start.
textBaseline:文字豎直對齊。可取屬性值:top, hanging, middle,
alphabetic, ideographic, bottom。預設值:alphabetic.
有兩個方法可以繪製文字: fillText 和 strokeText。第一個繪製帶 fillStyle 填充的文字,後者繪製只有 strokeStyle 邊框的文字。兩者的參數相同:要繪製的文字和文字的位置(x,y) 座標。還有一個可選選項——最大寬度。如果需要的話,瀏覽器會縮減文字以讓它適應指定寬度。
文字對齊屬性影響文字與設定的
(x,y) 座標的相對位置。
下面是一個在 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:設定陰影模糊程度。此值越大,陰影越模糊。其效果和 Photoshop 的高斯模糊濾鏡相同。
shadowOffsetX 和 shadowOffsetY:陰影的 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 陰影製作效果——藍色矩形,紅色陰影
色彩坡形
除了 CSS 顏色, fillStyle 和 strokeStyle 屬性可以設定為 CanvasGradient 對象。——通過 CanvasGradient可以為線條和填充使用色彩坡形。
欲建立 CanvasGradient 對象,可以使用兩個方法:createLinearGradient 和 createRadialGradient。前者建立線性色彩坡形,後者建立圓形色彩坡形。
建立色彩坡形對象後,可以使用對象的 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'); // redgradient1.addColorStop(0.5, '#ff0'); // yellowgradient1.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.
我也準備了一個更複雜的例子,使用了線性色彩坡形、陰影和文字。其效果見圖 7。
圖 7: 使用線性色彩坡形的例子