canvas教程

[HTML5资料]Canvas教程.pdf

字号+ 作者:H5之家 来源:H5之家 2017-01-23 12:03 我要评论( )

HTML资料Canvas教程canvas是一个新的用于通过脚本(通常是JavaScript)绘图的HTML元素。例如他可以用于绘图、制作图片的组合或者简单

HTML5资料1Canvas教程<canvas>是一个新的用于通过脚本(通常是JavaScript)绘图的HTML元素。例如,他可以用于绘图、制作图片的组合或者简单的动画(当然并不那么简单)。Itcanforinstancebeusedtodrawgraphs,makephotocompositionsordosimple(andnotsosimple)animations.1.1基本用法Basicusage<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>1.2绘图Drawingshapes绘制图形网格ThegridBeforewecanstartdrawing,weneedtotalkaboutthecanvasgridorcoordinatespace.TheHTMLtemplateonthepreviouspagehadacanvaselement150pixelswideand150pixelshigh.I'vedrawnthisimagewiththedefaultgridoverlayed.Normally1unitinthegridcorrespondsto1pixelonthecanvas.Theoriginofthisgridispositionedinthetopleftcorner(coordinate(0,0)).Allelementsareplacedrelativetothisorigin.Sothepositionofthetopleftcornerofthebluesquarebecomesxpixelsfromtheleftandypixelsfromthetop(coordinate(x,y)).Laterinthistutorialwe'llseehowwecantranslatetheorigintoadifferentposition,rotatethegridandevenscaleit.Fornowwe'llsticktothedefault.在真正开始之前,我们需要先探讨canvas的网格(grid)或者坐标空间(coordinatespace)。在前一页的HTML模板里有一个150像素宽,150像素高的canvas对象。我在画面上叠加上默认网格,如右图。通常网格的1个单元对应canvas上的1个像素。网格的原点是定位在左上角(坐标(0,0))。画面里的所有物体的位置都是相对这个原点。这样,左上角的蓝色方块的位置就是距左边x像素和距上边Y像素(坐标(x,y))。后面的教程中我们将学会如何把移动原点,旋转以及缩放网格。不过现在我们会使用默认的状态。绘制图形DrawingshapesUnlikeSVG,canvasonlysupportsoneprimitiveshape-rectangles.Allothershapesmustbecreatedbycombiningoneormorepaths.Luckily,wehaveacollectionofpathdrawingfunctionswhichmakeitpossibletocomposeverycomplexshapes.不像SVG,canvas只支持一种基本形状——矩形,所以其它形状都是有一个或多个路径组合而成。还好,有一组路径绘制函数让我们可以绘制相当复杂的形状。矩形RectanglesFirstlet'slookattherectangle.Therearethreefunctionsthatdrawrectanglesonthecanvas:我们首先看看矩形吧,有三个函数用于绘制矩形的:fillRect(x,y,width,height):DrawsafilledrectanglestrokeRect(x,y,width,height):DrawsarectangularoutlineclearRect(x,y,width,height):ClearsthespecifiedareaandmakesitfullytransparentEachofthesethreefunctionstakesthesameparameters.xandyspecifythepositiononthecanvas(relativetotheorigin)ofthetop-leftcorneroftherectangle.widthandheightareprettyobvious.Let'sseethesefunctionsinaction.它们都接受四个参数,x和y指定矩形左上角(相对于原点)的位置,width和height是矩形的宽和高。好,实战一下吧。Belowisthedraw()functionfromthepreviouspage,butnowI'veaddedthethreefunctionsabove.下面就是上页模板里的draw()函数,但添加了上面的三个函数。绘制矩形的例子Rectangularshapeexample观看示例functiondraw(){varcanvas=document.getElementById('tutorial');if(canvas.getContext){varctx=canvas.getContext('2d');ctx.fillRect(25,25,100,100);ctx.clearRect(45,45,60,60);ctx.strokeRect(50,50,50,50);}}Theresultshouldlooksomethingliketheimageontheright.ThefillRectfunctiondrawsalargeblacksquare100x100pixels.TheclearRectfunctionremovesa60x60pixelssquarefromthecenterandfinallythestrokeRectdrawsarectangularoutline50x50pixelsinsidetheclearedsquare.Inthefollowingpageswe'llseetwoalternativemethodsfortheclearRectfunctionandwe'llalsoseehowtochangethecolorandstrokestyleoftherenderedshapes.出来的结果应该和右边的是一样的。fillRect函数画了一个大的黑色矩形(100x100),clearRect函数清空了中间60x60大小的方块,然后strokeRect函数又在清空了的空间内勾勒出一个50x50的矩形边框。在接下去的页面里,我们会看到和clearRect函数差不多另外两个方法,以及如何去改变图形的填充和边框颜色。Unlikethepathfunctionswe'llseeinthenextsection,allthreerectanglefunctionsdrawimmediatelytothecanvas.与下一节的路径函数不一样,这三个函数的效果会立刻在canvas上反映出来。绘制路径DrawingpathsTomakeshapesusingpaths,weneedacoupleofextrasteps.不像画矩形那样的直截了当,绘制路径是需要一些额外的步骤的。beginPath()closePath()stroke()fill()ThefirststeptocreateapathiscallingthebeginPathmethod.Internally,pathsarestoredasalistofsub-paths(lines,arcs,etc)whichtogetherformashape.Everytimethismethodiscalled,thelistisresetandwecanstartdrawingnewshapes.第一步是用beginPath创建一个路径。在内存里,路径是以一组子路径(直线,弧线等)的形式储存的,它们共同构成一个图形。每次调用beginPath,子路径组都会被重置,然后可以绘制新的图形。Thesecondstepiscallingthemethodsthatactuallyspecifythepathstobedrawn.We'llseetheseshortly.第二步就是实际绘制路径的部分,很快我们就会看到。Thethird,andanoptionalstep,wouldbetocalltheclosePathmethod.Thismethodtriestoclosetheshapebydrawingastraightlinefromthecurrentpointtothestart.Iftheshapehasalreadybeenclosedorthere'sonlyonepointinthelist,thisfunctiondoesnothing.第三步是调用closePath方法,它会尝试用直线连接当前端点与起始端点来关闭路径,但如果图形已经关闭或者只有一个点,它会什么都不做。这一步不是必须的。Thefinalstepwillbecallingthestrokeand/orfillmethods.Callingoneofthesewillactuallydrawtheshapetothecanvas.strokeisusedtodrawanoutlinedshape,whilefillisusedtopaintasolidshape.最后一步是调用stroke或fill方法,这时,图形才是实际的绘制到canvas上去。stroke是绘制图形的边框,fill会用填充出一个实心图形。Note:Whencallingthefillmethodanyopenshapeswillbeclosedautomaticallyanditisn'tnecessarytousetheclosePathmethod.注意:当调用fill时,开放的路径会自动闭合,而无须调用closePath。Thecodeforadrawingsimpleshape(atriangle)wouldlooksomethinglikethis.画一个简单图形(如三角形)的代码如下。ctx.beginPath();ctx.moveTo(75,50);ctx.lineTo(100,75);ctx.lineTo(100,25);ctx.fill();moveToOneveryusefulfunction,whichdoesn'tactuallydrawanything,butispartofthepathlistdescribedabove,isthemoveTofunction.Youcanprobablybestthinkofthisasliftingapenorpencilfromonespotonapieceofpaperandplacingitonthenext.moveTo是一个十分有用的方法,虽然并不能用它来画什么,但却是绘制路径的实用方法的一部分。你可以把它想象成是把笔提起,并从一个点移动到另一个点的过程。moveTo(x,y)ThemoveTofunctiontakestwoarguments-xandy,-whicharethecoordinatesofthenewstartingpoint.它接受x和y(新的坐标位置)作为参数。WhenthecanvasisinitializedorthebeginPathmethodiscalled,thestartingpointissettothecoordinate(0,0).InmostcaseswewouldusethemoveTomethodtoplacethestartingpointsomewhereelse.WecouldalsousethemoveTomethodtodrawunconnectedpaths.Takealookatthesmileyfaceontheright.I'vemarkedtheplaceswhereIusedthemoveTomethod(theredlines).当canvas初始化或者调用beginPath的时候,起始坐标设置就是原点(0,0)。大多数情况下,我们用moveTo方法将起始坐标移至其它地方,或者用于绘制不连续的路径。看看右边的笑脸,红线就是使用moveTo移动的轨迹。Totrythisforyourself,youcanusethecodesnippetbelow.Justpasteitintothedrawfunctionwesawearlier.试一试下面的代码,粘贴到之前用过的draw函数内在看看效果吧。moveTo的使用示例观看示例ctx.beginPath();ctx.arc(75,75,50,0,Math.PI*2,true);//Outercirclectx.moveTo(110,75);ctx.arc(75,75,35,0,Math.PI,false);//Mouth(clockwise)ctx.moveTo(65,65);ctx.arc(60,65,5,0,Math.PI*2,true);//Lefteyectx.moveTo(95,65);ctx.arc(90,65,5,0,Math.PI*2,true);//Righteyectx.stroke();//thegoneheart完整例子ctx.beginPath();ctx.arc(75,75,50,0,Math.PI*2,true);//Outercirclectx.moveTo(110,75);ctx.arc(75,75,35,0,Math.PI,false);//Mouth(clockwise)ctx.moveTo(65,65);ctx.arc(60,65,5,0,Math.PI*2,true);//Lefteyectx.moveTo(95,65);ctx.arc(90,65,5,0,Math.PI*2,true);//Righteyectx.stroke();ctx.beginPath();ctx.moveTo(40,75);ctx.lineTo(60,65);ctx.lineTo(90,65);ctx.moveTo(110,75);ctx.lineTo(125,75);ctx.stroke();Note:removethemoveTomethodstoseetheconnectinglines.Note:Foradescriptionofthearcfunctionanditsparameterslookbelow.注意:你可以注释moveTo方法来观察那些连接起来的线。注意:arc方法的用法见下面。绘制各种线条LinesFordrawingstraightlinesweusethelineTomethod.我们用lineTo方法来画直线。lineTo(x,y)Thismethodtakestwoarguments-xandy,-whicharethecoordinatesoftheline'sendpoint.Thestartingpointisdependentonpreviousdrawnpaths,wheretheendpointofthepreviouspathisthestartingpointforthefollowing,etc.ThestartingpointcanalsobechangedbyusingthemoveTomethod.lineTo方法接受终点的坐标(x,y)作为参数。起始坐标取决于前一路径,前一路径的终点即当前路径的起点,起始坐标也可以通过moveTo方法来设置。lineTo的使用示例Intheexamplebelowtwotrianglesaredrawn,onefilledandoneoutlined.(Theresultcanbeseenintheimageontheright).FirstthebeginPathmethodiscalledtobeginanewshapepath.WethenusethemoveTomethodtomovethestartingpointtothedesiredposition.Belowthistwolinesaredrawnwhichmakeuptwosidesofthetriangle.示例(如右图)画的是两个三角形,一个实色填充,一个勾边。首先调用beginPath方法创建一个新路径,然后用moveTo方法将起始坐标移至想要的位置,然后画两条直线来构成三角形的两条边。You'llnoticethedifferencebetweenthefilledandstrokedtriangle.Thisis,asmentionedabove,becauseshapesareautomaticallyclosedwhenapathisfilled.Ifwewouldhavedonethisforthestrokedtriangleonlytwolineswouldhavebeendrawn,notacompletetriangle.可以注意到fill和strok绘三角形的区别,上面也提到过,使用fill路径会自动闭合,但使用stroke不会,如果不关闭路径,勾画出来的只有两边。观看示例//填充三角形ctx.beginPath();ctx.moveTo(25,25);ctx.lineTo(105,25);ctx.lineTo(25,105);ctx.fill();//勾边三角形ctx.beginPath();ctx.moveTo(125,125);ctx.lineTo(125,45);ctx.lineTo(45,125);ctx.closePath();ctx.stroke();弧线ArcsFordrawingarcsorcirclesweusethearcmethod.ThespecificationalsodescribesthearcTomethod,whichissupportedbySafaributhasn'tbeenimplementedinthecurrentGeckobrowsers.我们用arc方法来绘制弧线或圆。标准说明中还包含arcTo方法,当前Safari是支持的,但基于Gecko的浏览器还未实现。arc(x,y,radius,startAngle,endAngle,anticlockwise)Thismethodtakesfiveparameters:xandyarethecoordinatesofthecircle'scenter.Radiusisselfexplanatory.ThestartAngleandendAngleparametersdefinethestartandendpointsofthearcinradians.Thestartingandclosinganglearemeasuredfromthexaxis.Theanticlockwiseparameterisabooleanvaluewhichwhentruedrawsthearcanticlockwise,otherwiseinaclockwisedirection.方法接受五个参数:x,y是圆心坐标,radius是半径,startAngle和endAngle分别是起末弧度(以x轴为基准),anticlockwise为true表示逆时针,反之顺时针。Warning:IntheFirefoxbetabuilds,thelastparameterisclockwise.Thefinalreleasewillsupportthefunctionasdescribedabove.Allscriptsthatusethismethodinitscurrentformwillneedtobeupdatedoncethefinalversionisreleased.警告:在Firefox的beta版本里,最后一个参数是clockwise,而最终版本不是。因此如果是从beta升级至发行版需要做相应修改。Note:Anglesinthearcfunctionaremeasuredinradians,notdegrees.ToconvertdegreestoradiansyoucanusethefollowingJavaScriptexpression:varradians=(Math.PI/180)*degrees.注意:arc方法里用到的角度是以弧度为单位而不是度。度和弧度直接的转换可以用这个表达式:varradians=(Math.PI/180)*degrees;。arc的使用示例Thefollowingexampleisalittlemorecomplexthantheoneswe'veseenabove.I'vedrawn12differentarcsallwithdifferentanglesandfills.IfIwouldhavewrittenthisexamplejustlikethesmileyfaceabove,firstlythiswouldhavebecomeaverylonglistofstatementsandsecondly,whendrawingarcs,Iwouldneedtoknoweverysinglestartingpoint.Forarcsof90,180and270degrees,liketheonesIusedhere,thiswouldn'tbetomuchofaproblem,butformorecomplexonesthisbecomeswaytoodifficult.这个示例比之前见到过的要复杂一些,画了12个不同的弧形,有不同夹角和填充状态的。如果我用上面画笑脸的方式来画这些弧形,那会是一大段的代码,而且,画每一个弧形时我都需要知道其圆心位置。像我这里画90,180和270度的弧形看起来不是很麻烦,但是如果图形更复杂一些,则实现起来会越来越困难。Thetwoforloopsareforloopingthroughtherowsandcolumnsofarcs.ForeveryarcIstartanewpathusingbeginPath.Belowt

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • 【分享】深入浅出WPF全系列教程及源代码

    【分享】深入浅出WPF全系列教程及源代码

    2016-07-09 18:00

  • demo 一个画布的源代码,就是在 上绘制图形。 Graph Drawing 绘

    demo 一个画布的源代码,就是在 上绘制图形。 Graph Drawing 绘

    2016-06-07 12:06

  • VCGameDesign Visual C++游戏设计入门配套光盘源代码,学习VC 编

    VCGameDesign Visual C++游戏设计入门配套光盘源代码,学习VC 编

    2015-11-11 11:05

  • HTML5从入门到精通中文教程 pdf

    HTML5从入门到精通中文教程 pdf

    2015-11-09 18:09

网友点评