HTML5 規範引進了很多新特性,其中最令人期待的之一就是canvas 元素。 HTML 5 canvas 提供了通過JavaScript 繪製圖形的方法,此方法使用簡單但功能強大。每一個canvas 元素都有一個上下文( context ) (想像成繪圖板上的一頁),在其中可以繪製任意圖形。瀏覽器支持多個canvas 上下文,並通過不同的API 提供圖形繪製功能。大部分的瀏覽器都支持2D canvas 上下文-包括Opera, Firefox, Konqueror 和Safari。而且某些版本的Opera 還支持3D canvas ,Firefox 也可以通過插件形式支持3D canvas
本文介紹2D canvas基礎以及如何使用基本canvas 函數,如線條、形狀、圖像和文字等。為了理解此文章,你最好了解JavaScript 基礎知識。
可以點擊此處批量下載本文實例代碼
| 本文中的例子的超鏈接連接到網址全是HTML5網頁,目前支持HTML5的瀏覽器有Chrom,FireFox 3.6等,IE目前不支持HTML5,也就是說你用IE看本頁面的一些例子的超鏈接是看不到的。 |
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。通過fillRect可以繪製帶填充的矩形。使用strokeRect 可以繪製只有邊框沒有填充的矩形。如果想清除部分canvas 可以使用clearRect。上述三個方法的參數相同:x, y, width, height。前兩個參數設定(x,y) 坐標,後兩個參數設置矩形的高度和寬度。可以使用lineWidth屬性改變線條粗細。讓我們看看使用了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);
此例子效果圖見下圖:
路徑:
通過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) 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();
其效果圖見下圖:
另一個較複雜的例子中使用了直線、曲線和圓弧。
插入圖像:
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);
其效果見下圖:
像素級操作:
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);
下圖顯示了使用此濾鏡後的效果:
文字:
雖然最近的WebKit 版本和Firefox 3.1 nightly build 才開始支持Text API ,為了保證文章完整性我決定仍在這裡介紹文字API 。
context對象可以設置以下text 屬性:
font:文字字體,同CSSfont-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);
下圖是其效果圖:
陰影:
目前只有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);
其效果見下圖:
顏色漸變:
除了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'); // 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.
我也準備了一個更複雜的例子,使用了線性顏色漸變、陰影和文字。
其效果見下圖:
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
小節:
Canvas 是HTML 5最讓人期待的特性之一,目前已獲得大部分Web 瀏覽器支持。 Canvas 可以幫助創建遊戲、增強圖形用戶界面。 2D context
API 提供大量圖形繪製功能-我希望通過本文你了解了canvas 使用,並且你有興趣了解更多!