5 規範引進了很多新特性,其中最令人期待的之一就是canvas元素。 html5 canvas提供了通過javascript 繪製圖形的方法,此方法使用簡單但功能強大。每一個canvas元素都有一個上下文( context ) (想像成繪圖板上的一頁),在其中可以繪製任意圖形。瀏覽器支持多個canvas 上下文,並通過不同的提供圖形繪製功能。提供圖形繪製功能。 5 規範引進了很多新特性,其中最令人期待的之一就是元素。 html5 提供了通過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 :文字豎直對齊方式。可取屬性值: 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可以做些什麼,可以參看以下的工程:
sketchbook
demo, open-source
flight
canvas 是html5最讓人期待的特性之一,目前已獲得大部分web 瀏覽器支持。 canvas 可以幫助創建遊戲、增強圖形用戶界面。 2d context
api 提供大量圖形繪製功能-我希望通過本文你了解了canvas 使用,並且你有興趣了解更多!