欢迎来到天天文库
浏览记录
ID:33909978
大小:490.48 KB
页数:81页
时间:2019-03-01
《[HTML5资料]Canvas入门基础教程》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
HTML5资料1Canvas教程是一个新的用于通过脚本(通常是JavaScript)绘图的HTML元素。例如,他可以用于绘图、制作图片的组合或者简单的动画(当然并不那么简单)。Itcanforinstancebeusedtodrawgraphs,makephotocompositionsordosimple(andnotsosimple)animations.1.1基本用法Basicusage元素Let'sstartthistutorialbylookingattheelementitself.让我们从元素的定义开始吧。Thislooksalotliketheelement,theonlydifferenceisthatitdoesn'thavethesrcandaltattributes.看起来很像,唯一不同就是它不含src和alt属性。Theelementhasonlytwoattributes-widthandheight.ThesearebothoptionalandcanalsobesetusingDOMpropertiesorCSSrules.它只有两个属性,width和height,两个都是可选的,并且都可以DOM或者CSS来设置。Whennowidthandheightattributesarespecified,thecanvaswillinitiallybe300pixelswideand150pixelshigh.如果不指定width和height,默认的是宽300像素,高150像素。TheelementcanbesizedarbitrarilybyCSS,butduringrenderingtheimageisscaledtofititslayoutsize.(Ifyourrenderingsseemdistorted,tryspecifyingyourwidthandheightattributesexplicitlyintheattributes,andnotwithCSS.)虽然可以通过CSS来调整canvas的大小,但渲染图像会缩放来适应布局的(如果你发现渲染结果看上去变形了,不必一味依赖CSS,可以尝试显式指定canvas的width和height属性值)。Theidattributeisn'tspecifictotheelementbutisoneofdefaultHTMLattributeswhichcanbeappliedto(almost)everyHTMLelement(likeclassforinstance).It'salwaysagoodideatosupplyanidbecausethismakesitmucheasiertoidentifyitinourscript.id属性不是专享的,就像标准的HTLM标签一样,任何一个HTML元素都可以指定其id值。一般,为元素指定id是个不错的主意,这样使得在脚本中应用更加方便。Theelementcanbestyledjustlikeanynormalimage(margin,border,background,etc).Theseruleshoweverdon'taffecttheactualdrawingonthecanvas.We'llseehowthisisdonelaterinthistutorial.Whennostylingrulesareappliedtothecanvasitwillinitiallybefullytransparent.元素可以像普通图片一样指定其样式(边距,边框,背景等等)。然而这些样式并不会对canvas实际 生成的图像产生什么影响。下面我们会看到如何应用样式。如果不指定样式,canvas默认是全透明的。替用内容Becausetheelementisstillrelativelynewandisn'timplementedinsomebrowsers(suchasFirefox1.0andInternetExplorer),weneedameansofprovidingfallbackcontentwhenabrowserdoesn'tsupporttheelement.因为相对较新,有些浏览器并没实现,如Firefox1.0和InternetExplorer,所以我们需要为那些不支持canvas的浏览器提供替用显示内容。Luckilythisisverystraightforward:wejustprovidealternativecontentinsidethecanvaselement.Browserswhodon'tsupportitwillignoretheelementcompletelyandrenderthefallbackcontent,otherswilljustrenderthecanvasnormally.Forinstancewecouldprovideatextdescriptionofthecanvascontentorprovideastaticimageofthedynamicallyrenderedcontent.Thiscanlooksomethinglikethis:我们只需要直接在canvas元素内插入替用内容即可。不支持canvas的浏览器会忽略canvas元素而直接渲染替用内容,而支持的浏览器则会正常地渲染canvas。例如,我们可以把一些文字或图片填入canvas内,作为替用内容:currentstockprice:$3.15+0.15结束标签是必须的IntheAppleSafariimplementation,isanelementimplementedinmuchthesamewayis;itdoesnothaveanendtag.However,fortohavewidespreaduseontheweb,somefacilityforfallbackcontentmustbeprovided.Therefore,Mozilla'simplementationrequiresanendtag().在AppleSafari里,的实现跟很相似,它并不没有结束标签。然而,为了使能在web的世界里广泛适用,需要给替用内容提供一个容身之所,因此,在Mozilla的实现里结束标签()是必须的。 Iffallbackcontentisnotneeded,asimplewillbefullycompatiblewithbothSafariandMozilla--Safariwillsimplyignoretheendtag.如果没有替用内容,对Safari和Mozilla是完全兼容的——Safari会简单地忽略结束标签。Iffallbackcontentisdesired,someCSStricksmustbeemployedtomaskthefallbackcontentfromSafari(whichshouldrenderjustthecanvas),andalsotomasktheCSStricksthemselvesfromIE(whichshouldrenderthefallbackcontent).如果有替用内容,那么可以用一些CSS技巧来为并且仅为Safari隐藏替用内容,因为那些替用内容是需要在IE里显示但不需要在Safari里显示。渲染上下文(RenderingContext)createsafixedsizedrawingsurfacethatexposesoneormorerenderingcontexts,whichareusedtocreateandmanipulatethecontentshown.We'llfocusonthe2Drenderingcontext,whichistheonlycurrentlydefinedrenderingcontext.Inthefuture,othercontextsmayprovidedifferenttypesofrendering;forexample,itislikelythata3DcontextbasedonOpenGLESwillbeadded.创建的固定尺寸的绘图画面开放了一个或多个渲染上下文(renderingcontext),我们可以通过它们来控制要显示的内容。我们专注于2D渲染上,这也是目前唯一的选择,可能在将来会添加基于OpenGLES的3D上下文。Theisinitiallyblank,andtodisplaysomethingascriptfirstneedstoaccesstherenderingcontextanddrawonit.ThecanvaselementhasaDOMmethodcalledgetContext,usedtoobtaintherenderingcontextanditsdrawingfunctions.getContext()takesoneparameter,thetypeofcontext.初始化是空白的,要在上面用脚本画图首先需要其渲染上下文(renderingcontext),它可以通过canvas元素对象的getContext方法来获取,同时得到的还有一些画图用的函数。getContext()接受一个用于描述其类型的值作为参数。varcanvas=document.getElementById('tutorial');varctx=canvas.getContext('2d');InthefirstlineweretrievethecanvasDOMnodeusingthegetElementByIdmethod.WecanthenaccessthedrawingcontextusingthegetContextmethod. 上面第一行通过getElementById方法取得canvas对象的DOM节点。然后通过其getContext方法取得其画图操作上下文。检查浏览器的支持Thefallbackcontentisdisplayedinbrowserswhichdonotsupport;scriptscanalsocheckforsupportwhentheyexecute.ThiscaneasilybedonebytestingforthegetContextmethod.Ourcodesnippetfromabovebecomessomethinglikethis:除了在那些不支持的浏览器上显示替用内容,还可以通过脚本的方式来检查浏览器是否支持canvas。方法很简单,判断getContext是否存在即可。varcanvas=document.getElementById('tutorial');if(canvas.getContext){varctx=canvas.getContext('2d');//drawingcodehere}else{//canvas-unsupportedcodehere}代码模板Hereisaminimalistictemplate,whichwe'llbeusingasastartingpointforlaterexamples.Youcandownloadthisfiletoworkwithonyoursystem.我们会用下面这个最简化的代码模板来(后续的示例需要用到)作为开始,你可以下载文件到本地备用。Canvastutorialfunctiondraw(){varcanvas=document.getElementById('tutorial');if(canvas.getContext){varctx=canvas.getContext('2d');} }canvas{border:1pxsolidblack;}