仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1553|回复: 9
打印 上一主题 下一主题

[HTML5] 来一发Canvas教程(3):Drawing shapes绘制图形

[复制链接]
蒙在股里 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-15 23:19:37 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
WHATWG致力于Web表单和应用程序,而W3C(WorldWideWebConsortium,万维网联盟)专注于XHTML2.0。在2006年,双方决定进行合作.来创建一个新版本的HTML。网页制造poluoluo文章简介:在真正入手下手之前,我们必要先切磋canvas的网格(grid)大概坐标空间(coordinatespace)。在前一页的HTML模板里有一个150像素宽,150像素高的canvas工具。
网格Thegrid

Beforewecanstartdrawing,weneedtotalkaboutthecanvasgridorcoordinatespace.TheHTMLtemplateonthepreviouspagehadacanvaselement150pixelswideand150pixelshigh.Ivedrawnthisimagewiththedefaultgridoverlayed.Normally1unitinthegridcorrespondsto1pixelonthecanvas.Theoriginofthisgridispositionedinthetopleftcorner(coordinate(0,0)).Allelementsareplacedrelativetothisorigin.Sothepositionofthetopleftcornerofthebluesquarebecomesxpixelsfromtheleftandypixelsfromthetop(coordinate(x,y)).Laterinthistutorialwellseehowwecantranslatetheorigintoadifferentposition,rotatethegridandevenscaleit.Fornowwellsticktothedefault.
在真正入手下手之前,我们必要先切磋canvas的网格(grid)大概坐标空间(coordinatespace)。在前一页的HTML模板里有一个150像素宽,150像素高的canvas工具。我在画面上叠加上默许网格,如右图。一般网格的1个单位对应canvas上的1个像素。网格的原点是定位在左上角(坐标(0,0))。画面里的一切物体的地位都是绝对这个原点。如许,左上角的蓝色方块的地位就是距右边x像素和距上边Y像素(坐标(x,y))。前面的教程中我们将学会怎样把挪动原点,扭转和缩放网格。不外如今我们会利用默许的形态。
绘制图形Drawingshapes

UnlikeSVG,canvasonlysupportsoneprimitiveshape-rectangles.Allothershapesmustbecreatedbycombiningoneormorepaths.Luckily,wehaveacollectionofpathdrawingfunctionswhichmakeitpossibletocomposeverycomplexshapes.
不像SVG,canvas只撑持一种基础外形——矩形,以是别的外形都是有一个或多个路径组合而成。还好,有一组路径绘制函数让我们能够绘制相称庞大的外形。
矩形Rectangles

Firstletslookattherectangle.Therearethreefunctionsthatdrawrectanglesonthecanvas:
我们起首看看矩形吧,有三个函数用于绘制矩形的:
fillRect(x,y,width,height):Drawsafilledrectangle
strokeRect(x,y,width,height):Drawsarectangularoutline
clearRect(x,y,width,height):Clearsthespecifiedareaandmakesitfullytransparent
Eachofthesethreefunctionstakesthesameparameters.xandyspecifythepositiononthecanvas(relativetotheorigin)ofthetop-leftcorneroftherectangle.widthandheightareprettyobvious.Letsseethesefunctionsinaction.
它们都承受四个参数,x和y指定矩形左上角(相对原点)的地位,width和height是矩形的宽和高。好,实战一下吧。
Belowisthedraw()functionfromthepreviouspage,butnowIveaddedthethreefunctionsabove.
上面就是上页模板里的draw()函数,但增加了下面的三个函数。
绘制矩形的例子Rectangularshapeexample

寓目示例
  1. 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.InthefollowingpageswellseetwoalternativemethodsfortheclearRectfunctionandwellalsoseehowtochangethecolorandstrokestyleoftherenderedshapes.
出来的了局应当和右侧的是一样的。fillRect函数画了一个年夜的玄色矩形(100x100),clearRect函数清空了两头60x60巨细的方块,然后strokeRect函数又在清空了的空间内勾画出一个50x50的矩形边框。在接下往的页面里,我们会看到和clearRect函数差未几别的两个办法,和怎样往改动图形的添补和边框色彩。
Unlikethepathfunctionswellseeinthenextsection,allthreerectanglefunctionsdrawimmediatelytothecanvas.
与下一节的路径函数纷歧样,这三个函数的效果会立即在canvas上反应出来。
绘制路径Drawingpaths

Tomakeshapesusingpaths,weneedacoupleofextrasteps.
不像画矩形那样的刀切斧砍,绘制路径是必要一些分外的步骤的。
beginPath()
closePath()
stroke()
fill()

ThefirststeptocreateapathiscallingthebeginPathmethod.Internally,pathsarestoredasalistofsub-paths(lines,arcs,etc)whichtogetherformashape.Everytimethismethodiscalled,thelistisresetandwecanstartdrawingnewshapes.
第一步是用beginPath创立一个路径。在内存里,路径是以一组子路径(直线,弧线等)的情势贮存的,它们配合组成一个图形。每次挪用beginPath,子路径组城市被重置,然后能够绘制新的图形。
Thesecondstepiscallingthemethodsthatactuallyspecifythepathstobedrawn.Wellseetheseshortly.
第二步就是实践绘制路径的部分,很快我们就会看到。
Thethird,andanoptionalstep,wouldbetocalltheclosePathmethod.Thismethodtriestoclosetheshapebydrawingastraightlinefromthecurrentpointtothestart.Iftheshapehasalreadybeenclosedortheresonlyonepointinthelist,thisfunctiondoesnothing.
第三步是挪用closePath办法,它会实验用直线毗连以后端点与肇端端点来封闭路径,但假如图形已封闭大概只要一个点,它会甚么都不做。这一步不是必需的。
Thefinalstepwillbecallingthestrokeand/orfillmethods.Callingoneofthesewillactuallydrawtheshapetothecanvas.strokeisusedtodrawanoutlinedshape,whilefillisusedtopaintasolidshape.
最初一步是挪用stroke或fill办法,这时候,图形才是实践的绘制到canvas上往。stroke是绘制图形的边框,fill会用添补出一个实心图形。
Note:WhencallingthefillmethodanyopenshapeswillbeclosedautomaticallyanditisntnecessarytousetheclosePathmethod.
注重:当挪用fill时,开放的路径会主动闭合,而不必挪用closePath。
Thecodeforadrawingsimpleshape(atriangle)wouldlooksomethinglikethis.
画一个复杂图形(如三角形)的代码以下。
  1. ctx.beginPath();ctx.moveTo(75,50);ctx.lineTo(100,75);ctx.lineTo(100,25);ctx.fill();
复制代码
moveTo

Oneveryusefulfunction,whichdoesntactuallydrawanything,butispartofthepathlistdescribedabove,isthemoveTofunction.Youcanprobablybestthinkofthisasliftingapenorpencilfromonespotonapieceofpaperandplacingitonthenext.
moveTo是一个非常有效的办法,固然其实不能用它来画甚么,但倒是绘制路径的有用办法的一部分。你能够把它设想成是把笔提起,并从一个点挪动到另外一个点的历程。
moveTo(x,y)
ThemoveTofunctiontakestwoarguments-xandy,-whicharethecoordinatesofthenewstartingpoint.
它承受x和y(新的坐标地位)作为参数。
WhenthecanvasisinitializedorthebeginPathmethodiscalled,thestartingpointissettothecoordinate(0,0).InmostcaseswewouldusethemoveTomethodtoplacethestartingpointsomewhereelse.WecouldalsousethemoveTomethodtodrawunconnectedpaths.Takealookatthesmileyfaceontheright.IvemarkedtheplaceswhereIusedthemoveTomethod(theredlines).
当canvas初始化大概挪用beginPath的时分,肇端坐标设置就是原点(0,0)。年夜多半情形下,我们用moveTo办法将肇端坐标移至别的中央,大概用于绘制不一连的路径。看看右侧的笑容,红线就是利用moveTo挪动的轨迹。
Totrythisforyourself,youcanusethecodesnippetbelow.Justpasteitintothedrawfunctionwesawearlier.
试一试上面的代码,粘贴到之前用过的draw函数内涵看看效果吧。
moveTo的利用示例
  1. 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();
复制代码
Note:removethemoveTomethodstoseetheconnectinglines.
Note:Foradescriptionofthearcfunctionanditsparameterslookbelow.
注重:你能够正文moveTo办法来察看那些毗连起来的线。
注重:arc办法的用法见上面。
直线Lines

FordrawingstraightlinesweusethelineTomethod.
我们用lineTo办法来画直线。
lineTo(x,y)
Thismethodtakestwoarguments-xandy,-whicharethecoordinatesofthelinesendpoint.Thestartingpointisdependentonpreviousdrawnpaths,wheretheendpointofthepreviouspathisthestartingpointforthefollowing,etc.ThestartingpointcanalsobechangedbyusingthemoveTomethod.
lineTo办法承受尽头的坐标(x,y)作为参数。肇端坐标取决于前一起径,前一起径的尽头即以后路径的出发点,肇端坐标也能够经由过程moveTo办法来设置。
lineTo的利用示例

Intheexamplebelowtwotrianglesaredrawn,onefilledandoneoutlined.(Theresultcanbeseenintheimageontheright).FirstthebeginPathmethodiscalledtobeginanewshapepath.WethenusethemoveTomethodtomovethestartingpointtothedesiredposition.Belowthistwolinesaredrawnwhichmakeuptwosidesofthetriangle.
示例(如右图)画的是两个三角形,一个实色添补,一个勾边。起首挪用beginPath办法创立一个新路径,然后用moveTo办法将肇端坐标移至想要的地位,然后画两条直线来组成三角形的两条边。
Youllnoticethedifferencebetweenthefilledandstrokedtriangle.Thisis,asmentionedabove,becauseshapesareautomaticallyclosedwhenapathisfilled.Ifwewouldhavedonethisforthestrokedtriangleonlytwolineswouldhavebeendrawn,notacompletetriangle.
能够注重到fill和strok绘三角形的区分,下面也提到过,利用fill路径会主动闭合,但利用stroke不会,假如不封闭路径,勾勒出来的只要双方。
寓目示例
  1. //添补三角形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();
复制代码
弧线Arcs

Fordrawingarcsorcirclesweusethearcmethod.ThespecificationalsodescribesthearcTomethod,whichissupportedbySafaributhasntbeenimplementedinthecurrentGeckobrowsers.
我们用arc办法来绘制弧线或圆。尺度申明中还包括arcTo办法,以后Safari是撑持的,但基于Gecko的扫瞄器还未完成。
arc(x,y,radius,startAngle,endAngle,anticlockwise)
Thismethodtakesfiveparameters:xandyarethecoordinatesofthecirclescenter.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的利用示例

Thefollowingexampleisalittlemorecomplexthantheonesweveseenabove.Ivedrawn12differentarcsallwithdifferentanglesandfills.IfIwouldhavewrittenthisexamplejustlikethesmileyfaceabove,firstlythiswouldhavebecomeaverylonglistofstatementsandsecondly,whendrawingarcs,Iwouldneedtoknoweverysinglestartingpoint.Forarcsof90,180and270degrees,liketheonesIusedhere,thiswouldntbetomuchofaproblem,butformorecomplexonesthisbecomeswaytoodifficult.
这个示例比之前见到过的要庞大一些,画了12个分歧的弧形,有分歧夹角和添补形态的。假如我用下面画笑容的体例来画这些弧形,那会是一年夜段的代码,并且,画每个弧形时我都必要晓得其圆心地位。像这里画90,180和270度的弧形一样是一个成绩,假如图形越冗杂完成起来会越坚苦。
Thetwoforloopsareforloopingthroughtherowsandcolumnsofarcs.ForeveryarcIstartanewpathusingbeginPath.BelowthisIvewrittenoutalltheparametersasvariables,soitseasiertoreadwhatsgoingon.Normallythiswouldbejustonestatement.Thexandycoordinatesshouldbeclearenough.radiusandstartAnglearefixed.TheendAnglestartsofas180degrees(firstcolumn)andisincreasedwithstepsof90degreestoformacompletecircle(lastcolumn).Thestatementfortheclockwiseparameterresultsinthefirstandthirdrowbeingdrawnasclockwisearcsandthesecondandfourthrowascounterclockwisearcs.Finally,theifstatementmakesthetophalfstrokedarcsandthebottomhalffilledarcs.
这里利用两个for轮回来画多行多列的弧形。每个弧形都用beginPath办法创立一个新路径。然后为了便利浏览和了解,我把一切参数都写成变量情势。不言而喻,x和y作为圆心坐标。radius和startAngle都是流动,endAngle从180度半圆入手下手,以90度体例递增至圆。anticlockwise则取决于奇偶行数。最初,经由过程if语句判别使前两行体现为勾边,尔后两举动添补效果。
  1. for(i=0;i<4;i++){for(j=0;j<3;j++){ctx.beginPath();varx=25+j*50;//xcoordinatevary=25+i*50;//ycoordinatevarradius=20;//ArcradiusvarstartAngle=0;//StartingpointoncirclevarendAngle=Math.PI+(Math.PI*j)/2;//Endpointoncirclevaranticlockwise=i%2==0?false:true;//clockwiseoranticlockwisectx.arc(x,y,radius,startAngle,endAngle,anticlockwise);if(i>1){ctx.fill();}else{ctx.stroke();}}}
复制代码
贝塞尔和二次方曲线Bezierandquadraticcurves

ThenexttypeofpathsavailableareB
简单生活 该用户已被删除
沙发
发表于 2015-1-17 11:48:33 | 只看该作者
Dreamweaver是唯一提供RoundtripHTML、视觉化编辑与原始码编辑同步的设计工具。它包含HomeSite和BBEdit等主流文字编辑器。
灵魂腐蚀 该用户已被删除
板凳
发表于 2015-1-20 18:51:11 | 只看该作者
Dreamweaver8中文版(dw)是由Macromedia公司开发的一款所见即所得的网页编辑器。和二维动画设计软件FLASH,专业网页图像设计软件FIREWORKS,并称为“网页三剑客”。
第二个灵魂 该用户已被删除
地板
发表于 2015-1-29 15:11:14 | 只看该作者
您在所见即所得网页编辑器进行网页制作和在WORD中进行文本编辑不会感到有什么区别,但它同时也存在着致命的弱点。
不帅 该用户已被删除
5#
发表于 2015-2-6 02:31:47 | 只看该作者
难以逾越的障碍会大大打击你的学习积极性。这就需要你的恒心,坚持不懈的决心。在自己无法解决某些问题时,就需要虚心请教别人.
若相依 该用户已被删除
6#
发表于 2015-2-15 04:15:41 | 只看该作者
学Dreamweaver技术的过程其实是一个增加信心的过程。
小魔女 该用户已被删除
7#
发表于 2015-3-4 11:21:19 | 只看该作者
每天上网看着那样多的网页,于是我才下定决心选择了网页制作这一门课程,目的就是希望以后能够做出一个完美的网页来。
谁可相欹 该用户已被删除
8#
发表于 2015-3-11 18:51:21 | 只看该作者
还可以在Dreamweaver常用工具中选择超级链接,完成相应的填写即可。
只想知道 该用户已被删除
9#
发表于 2015-3-19 08:30:46 | 只看该作者
Dreamweaver8中文版(dw)是由Macromedia公司开发的一款所见即所得的网页编辑器。和二维动画设计软件FLASH,专业网页图像设计软件FIREWORKS,并称为“网页三剑客”。
海妖 该用户已被删除
10#
发表于 2015-3-27 18:08:27 | 只看该作者
经过两天的学习,总算对Dreamweaver有进一步的了解了,心中不免有些激动。今天和其他几位老师交流了一下,感觉受益匪浅.
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-4-28 08:38

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表