HTML5资料Canvas教程.docx

上传人:b****1 文档编号:3458145 上传时间:2023-05-05 格式:DOCX 页数:90 大小:66.47KB
下载 相关 举报
HTML5资料Canvas教程.docx_第1页
第1页 / 共90页
HTML5资料Canvas教程.docx_第2页
第2页 / 共90页
HTML5资料Canvas教程.docx_第3页
第3页 / 共90页
HTML5资料Canvas教程.docx_第4页
第4页 / 共90页
HTML5资料Canvas教程.docx_第5页
第5页 / 共90页
HTML5资料Canvas教程.docx_第6页
第6页 / 共90页
HTML5资料Canvas教程.docx_第7页
第7页 / 共90页
HTML5资料Canvas教程.docx_第8页
第8页 / 共90页
HTML5资料Canvas教程.docx_第9页
第9页 / 共90页
HTML5资料Canvas教程.docx_第10页
第10页 / 共90页
HTML5资料Canvas教程.docx_第11页
第11页 / 共90页
HTML5资料Canvas教程.docx_第12页
第12页 / 共90页
HTML5资料Canvas教程.docx_第13页
第13页 / 共90页
HTML5资料Canvas教程.docx_第14页
第14页 / 共90页
HTML5资料Canvas教程.docx_第15页
第15页 / 共90页
HTML5资料Canvas教程.docx_第16页
第16页 / 共90页
HTML5资料Canvas教程.docx_第17页
第17页 / 共90页
HTML5资料Canvas教程.docx_第18页
第18页 / 共90页
HTML5资料Canvas教程.docx_第19页
第19页 / 共90页
HTML5资料Canvas教程.docx_第20页
第20页 / 共90页
亲,该文档总共90页,到这儿已超出免费预览范围,如果喜欢就下载吧!
下载资源
资源描述

HTML5资料Canvas教程.docx

《HTML5资料Canvas教程.docx》由会员分享,可在线阅读,更多相关《HTML5资料Canvas教程.docx(90页珍藏版)》请在冰点文库上搜索。

HTML5资料Canvas教程.docx

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.  (Ifyour renderingsseemdistorted,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.

我们会用下面这个最简化的代码模板来(后续的示例需要用到)作为开始,你可以下载文件到本地备用。

 

   Canvastutorial

   

     functiondraw(){

       varcanvas=document.getElementById('tutorial');

       if(canvas.getContext){

         varctx=canvas.getContext('2d');

       }

     }

   

   

     canvas{border:

1pxsolidblack;}

   

 

 

   

 

Ifyoulookatthescriptyou'llseeI'vemadeafunctioncalleddraw,whichwillgetexecutedoncethepagefinishesloading(viatheonloadattributeonthebodytag).ThisfunctioncouldalsohavebeencalledfromasetTimeout,setInterval,oranyothereventhandlerfunctionjustaslongthepagehasbeenloadedfirst.

细心的你会发现我准备了一个名为draw的函数,它会在页面装载完毕之后执行一次(通过设置body标签的onload属性),它当然也可以在setTimeout,setInterval,或者其他事件处理函数中被调用。

一个简单的例子

Tostartoff,here'sasimpleexamplethatdrawstwointersectingrectangles,oneofwhichhasalphatransparency.We'llexplorehowthisworksinmoredetailinlaterexamples.

作为开始,来一个简单的吧——绘制两个交错的矩形,其中一个是有alpha透明效果。

我们会在后面的示例中详细的让你了解它是如何运作的。

 

观看示例 

 

 

   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);

     }

   }

 

 

 

  

 

1.2绘图

Drawingshapes绘制图形

网格Thegrid

Beforewecanstartdrawing,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))。

后面的教程中我们将学会如何把移动原点,旋转以及缩放网格。

不过现在我们会使用默认的状态。

绘制图形Drawingshapes

UnlikeSVG,canvasonlysupportsoneprimitiveshape-rectangles.Allothershapesmustbecreatedbycombiningoneormorepaths.Luckily,wehaveacollectionofpathdrawingfunctionswhichmakeitpossibletocomposeverycomplexshapes.

不像SVG,canvas只支持一种基本形状——矩形,所以其它形状都是有一个或多个路径组合而成。

还好,有一组路径绘制函数让我们可以绘制相当复杂的形状。

矩形Rectangles

Firstlet'slookattherectangle.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.Let'sseethesefunctionsinaction.

它们都接受四个参数,x和y指定矩形左上角(相对于原点)的位置,width和height是矩形的宽和高。

好,实战一下吧。

Belowisthedraw()f

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 党团工作 > 入党转正申请

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2