<canvas>是一个新的HTML元素,这个元素可以被Script语言(通常是JavaScript)用来绘制图形。例如可以用它来画图、合成图象、或做简单的(和不那么简单的)动画。右面的图象展示了一些<canvas>的应用示例,我们将会在此教程中看到他们的实现。
<canvas>最先在苹果公司(Apple)的MacOSXDashboard上被引入,而后被应用于Safari。基于Gecko1.8的浏览器,例如Firefox1.5,也支持这个新元素。元素<canvas>是WhatWGWebapplications1.0也就是大家都知道的HTML5标准规范的一部分。
在本教程中,我将试着讲述如何在你自己的网页中使用<canvas>元素。提供的示例应该会给你些清晰概念,即用<canvas>能做些什么的。这些示例也可作为你应用<canvas>的起点。
开始使用之前
用元素<canvas>并不难,只要你具有HTML和JavaScript的基础知识。
如上所述,并不是所有现代浏览器都支持<canvas>元素,所以你需要Firefox1.5或更新版本、或者其他基于Gecko的浏览器例如Opera9、或者最近版本的Safari才能看到所有示例的动作。
<canvas>元素
Let'sstartthistutorialbylookingatthe<canvas>elementitself.
让我们从<canvas>元素的定义开始吧。
<canvasid="tutorial"width="150"height="150"></canvas>
Thislooksalotlikethe<img>element,theonlydifferenceisthatitdoesn'thavethesrcandaltattributes.<canvas>看起来很像<img>,唯一不同就是它不含src和alt属性。The<canvas>elementhasonlytwoattributes-widthandheight.ThesearebothoptionalandcanalsobesetusingDOMpropertiesorCSSrules.它只有两个属性,width和height,两个都是可选的,并且都可以DOM或者CSS来设置。Whennowidthandheightattributesarespecified,thecanvaswillinitiallybe300pixelswideand150pixelshigh.如果不指定width和height,默认的是宽300像素,高150像素。TheelementcanbesizedarbitrarilybyCSS,butduringrenderingtheimageisscaledtofititslayoutsize.(Ifyourrenderingsseemdistorted,tryspecifyingyourwidthandheightattributesexplicitlyinthe<canvas>attributes,andnotwithCSS.)虽然可以通过CSS来调整canvas的大小,但渲染图像会缩放来适应布局的(如果你发现渲染结果看上去变形了,不必一味依赖CSS,可以尝试显式指定canvas的width和height属性值)。
Theidattributeisn'tspecifictothe<canvas>elementbutisoneofdefaultHTMLattributeswhichcanbeappliedto(almost)everyHTMLelement(likeclassforinstance).It'salwaysagoodideatosupplyanidbecausethismakesitmucheasiertoidentifyitinourscript.
id属性不是<canvas>专享的,就像标准的HTLM标签一样,任何一个HTML元素都可以指定其id值。一般,为元素指定id是个不错的主意,这样使得在脚本中应用更加方便。
The<canvas>elementcanbestyledjustlikeanynormalimage(margin,border,background,etc).Theseruleshoweverdon'taffecttheactualdrawingonthecanvas.We'llseehowthisisdonelaterinthistutorial.Whennostylingrulesareappliedtothecanvasitwillinitiallybefullytransparent.<canvas>元素可以像普通图片一样指定其样式(边距,边框,背景等等)。然而这些样式并不会对canvas实际生成的图像产生什么影响。下面我们会看到如何应用样式。如果不指定样式,canvas默认是全透明的。
替用内容
Becausethe<canvas>elementisstillrelativelynewandisn'timplementedinsomebrowsers(suchasFirefox1.0andInternetExplorer),weneedameansofprovidingfallbackcontentwhenabrowserdoesn'tsupporttheelement.
因为<canvas>相对较新,有些浏览器并没实现,如Firefox1.0和InternetExplorer,所以我们需要为那些不支持canvas的浏览器提供替用显示内容。
Luckilythisisverystraightforward:wejustprovidealternativecontentinsidethecanvaselement.Browserswhodon'tsupportitwillignoretheelementcompletelyandrenderthefallbackcontent,otherswilljustrenderthecanvasnormally.
Forinstancewecouldprovideatextdescriptionofthecanvascontentorprovideastaticimageofthedynamicallyrenderedcontent.Thiscanlooksomethinglikethis:
我们只需要直接在canvas元素内插入替用内容即可。不支持canvas的浏览器会忽略canvas元素而直接渲染替用内容,而支持的浏览器则会正常地渲染canvas。例如,我们可以把一些文字或图片填入canvas内,作为替用内容:
<canvasid="stockGraph"width="150"height="150">
currentstockprice:$3.15+0.15
</canvas>
<canvasid="clock"width="150"height="150">
<imgsrc="images/clock.png"width="150"height="150"/>
</canvas>
结束标签</canvas>是必须的
IntheAppleSafariimplementation,<canvas>isanelementimplementedinmuchthesameway<img>is;itdoesnothaveanendtag.However,for<canvas>tohavewidespreaduseontheweb,somefacilityforfallbackcontentmustbeprovided.Therefore,Mozilla'simplementationrequiresanendtag(</canvas>).
在AppleSafari里,<canvas>的实现跟<img>很相似,它并不没有结束标签。然而,为了使<canvas>能在web的世界里广泛适用,需要给替用内容提供一个容身之所,因此,在Mozilla的实现里结束标签(</canvas>)是必须的。
Iffallbackcontentisnotneeded,asimple<canvasid="foo"...></canvas>willbefullycompatiblewithbothSafariandMozilla--Safariwillsimplyignoretheendtag.
如果没有替用内容,<canvasid="foo"...></canvas>对Safari和Mozilla是完全兼容的——Safari会简单地忽略结束标签。
Iffallbackcontentisdesired,someCSStricksmustbeemployedtomaskthefallbackcontentfromSafari(whichshouldrenderjustthecanvas),andalsotomasktheCSStricksthemselvesfromIE(whichshouldrenderthefallbackcontent).
如果有替用内容,那么可以用一些CSS技巧来为并且仅为Safari隐藏替用内容,因为那些替用内容是需要在IE里显示但不需要在Safari里显示。
渲染上下文(RenderingContext)
<canvas>createsafixedsizedrawingsurfacethatexposesoneormorerenderingcontexts,whichareusedtocreateandmanipulatethecontentshown.We'llfocusonthe2Drenderingcontext,whichistheonlycurrentlydefinedrenderingcontext.Inthefuture,othercontextsmayprovidedifferenttypesofrendering;forexample,itislikelythata3DcontextbasedonOpenGLESwillbeadded.
<canvas>创建的固定尺寸的绘图画面开放了一个或多个渲染上下文(renderingcontext),我们可以通过它们来控制要显示的内容。我们专注于2D渲染上,这也是目前唯一的选择,可能在将来会添加基于OpenGLES的3D上下文。
The<canvas>isinitiallyblank,andtodisplaysomethingascriptfirstneedstoaccesstherenderingcontextanddrawonit.ThecanvaselementhasaDOMmethodcalledgetContext,usedtoobtaintherenderingcontextanditsdrawingfunctions.getContext()takesoneparameter,thetypeofcontext.
<canvas>初始化是空白的,要在上面用脚本画图首先需要其渲染上下文(renderingcontext),它可以通过canvas元素对象的getContext方法来获取,同时得到的还有一些画图用的函数。getContext()接受一个用于描述其类型的值作为参数。
varcanvas=document.getElementById('tutorial');
varctx=canvas.getContext('2d');
InthefirstlineweretrievethecanvasDOMnodeusingthegetElementByIdmethod.WecanthenaccessthedrawingcontextusingthegetContextmethod.
上面第一行通过getElementById方法取得canvas对象的DOM节点。然后通过其getContext方法取得其画图操作上下文。
检查浏览器的支持
Thefallbackcontentisdisplayedinbrowserswhichdonotsupport<canvas>;scriptscanalsocheckforsupportwhentheyexecute.ThiscaneasilybedonebytestingforthegetContextmethod.Ourcodesnippetfromabovebecomessomethinglikethis:
除了在那些不支持的浏览器上显示替用内容,还可以通过脚本的方式来检查浏览器是否支持canvas。方法很简单,判断getContext是否存在即可。
varcanvas=document.getElementById('tutorial');
if(canvas.getContext){
varctx=canvas.getContext('2d');
//drawingcodehere
}else{
//canvas-unsupportedcodehere
}
代码模板
Hereisaminimalistictemplate,whichwe'llbeusingasastartingpointforlaterexamples.Youcandownloadthisfiletoworkwithonyoursystem.
我们会用下面这个最简化的代码模板来(后续的示例需要用到)作为开始,你可以下载文件到本地备用。
<html>
<head>
<title>Canvastutorial</title>
<scripttype="text/javascript">
functiondraw(){
varcanvas=document.getElementById('tutorial');
if(canvas.getContext){
varctx=canvas.getContext('2d');
}
}
</script>
<styletype="text/css">
canvas{border:1pxsolidblack;}
</style>
</head>
<bodyonload="draw();">
<canvasid="tutorial"width="150"height="150"></canvas>
</body>
</html>
Ifyoulookatthescriptyou'llseeI'vemadeafunctioncalleddraw,whichwillgetexecutedoncethepagefinishesloading(viatheonloadattributeonthebodytag).ThisfunctioncouldalsohavebeencalledfromasetTimeout,setInterval,oranyothereventhandlerfunctionjustaslongthepagehasbeenloadedfirst.
细心的你会发现我准备了一个名为draw的函数,它会在页面装载完毕之后执行一次(通过设置body标签的onload属性),它当然也可以在setTimeout,setInterval,或者其他事件处理函数中被调用。
一个简单的例子
Tostartoff,here'sasimpleexamplethatdrawstwointersectingrectangles,oneofwhichhasalphatransparency.We'llexplorehowthisworksinmoredetailinlaterexamples.
作为开始,来一个简单的吧——绘制两个交错的矩形,其中一个是有alpha透明效果。我们会在后面的示例中详细的让你了解它是如何运作的。
<html>
<head>
<scripttype="application/x-javascript">
functiondraw(){
varcanvas=document.getElementById("canvas");
if(canvas.getContext){
varctx=canvas.getContext("2d");
ctx.fillStyle="rgb(200,0,0)";
ctx.fillRect(10,10,55,50);
ctx.fillStyle="rgba(0,0,200,0.5)";
ctx.fillRect(30,30,55,50);
}
}
</script>
</head>
<bodyonload="draw();">
<canvasid="canvas"width="150"height="150"></canvas>
</body>
</html>点这里查看更多HTML教程