5 規范引進了很多新特性,其中最令人期待的之一就是 canvas
元素。html 5 canvas
提供了通過 javascript 繪制圖形的方法,此方法使用簡單但功能強大。每一個 canvas
元素都有一個"上下文( context )" (想象成繪圖板上的一頁),在其中可以繪制任意圖形。瀏覽器支持多個 canvas 上下文,并通過不同的 提供圖形繪制功能。 提供圖形繪制功能。 5 規范引進了很多新特性,其中最令人期待的之一就是 元素。html 5 提供了通過 javascript 繪制圖形的方法,此方法使用簡單但功能強大。每一個 元素都有一個"上下文( context )" (想象成繪圖板上的一頁),在其中可以繪制任意圖形。瀏覽器支持多個 canvas 上下文,并通過不同的 提供圖形繪制功能。
大部分的瀏覽器都支持 2d canvas 上下文——包括 opera, firefox, konqueror 和 safari。而且某些版本的 opera 還支持 3d canvas ,firefox 也可以通過插件形式支持 3d canvas :
本文介紹 2d canvas
基礎以及如何使用基本 canvas 函數,如線條、形狀、圖像和文字等。為了理解此文章,你最好了解 javascript 基礎知識。
可以點擊此處批量下載本文實例代碼
創建 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
部分中,或者放在外部文件中。
介紹了如何創建 canvas 后,讓我們來看看 2d canvas api,看看能用這些函數做些什么。
上面的例子中展示了繪制矩形是多么簡單。
通過 fillstyle 和 strokestyle 屬性可以輕松的設置矩形的填充和線條。顏色值使用方法和 十六進制數、()、() 和 ()( 若瀏覽器支持,如 opera
10 和 firefox 3)。()( 若瀏覽器支持,如 opera10 和 firefox 3)。() 和 ()( 若瀏覽器支持,如 opera10 和 firefox 3)。()、() 和 ()( 若瀏覽器支持,如 opera10 和 firefox 3)。十六進制數、()、() 和 ()( 若瀏覽器支持,如 opera10 和 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個參數:
drawimage
使用方法。一個參數指定圖像位置,另兩個參數設置圖像在 canvas中的位置。 drawimage
使用方法,包括上面所述3個參數,加兩個參數指明插入圖像寬度和高度 (如果你想改變圖像大小)。 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
:文字字體,同font-family
屬性 屬性 textalign
:文字水平對齊方式。可取屬性值: start
, end
, left
,right
, center
。默認值:start
. textbaseline
:文字豎直對齊方式??扇傩灾担?code>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: 使用線性顏色漸變的例子
如果你想知道使用 canvas可以做些什么,可以參看以下的工程:
canvas 是 html 5最讓人期待的特性之一,目前已獲得大部分 web 瀏覽器支持。canvas 可以幫助創建游戲、增強圖形用戶界面。2d context
api 提供大量圖形繪制功能——我希望通過本文你了解了 canvas 使用,并且你有興趣了解更多!
新聞熱點
疑難解答