|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
HTML5开发的网页文档类型极其简单,就够了,记得5年前还在反复跟团队强调使用XHTML那段冗长的文档类型声明.网页制造poluoluo文章简介:Canvas相称风趣的一项功效就是能够引进图象,它能够用于图片分解大概制造背景等。而今朝仅能够在图象中到场笔墨(尺度申明中并没有包括绘制笔墨的功效)。只需是Gecko撑持的图象(如PNG,GIF,JPEG等)都能够引进到canvas中,并且别的的canvas元素也能够作为图
使用图象Usingimages
Oneofthemorefunfeaturesofthecanvasistheabillitytouseimages.Thesecanbeusedtododynamicphotocompositingorusedasbackdropsofgraphsetc.Itscurrentlyalsotheonlywaytoaddtexttothem(Thespecificationdoesnotcontainanyfunctionstodrawtext).ExternalimagescanbeusedinanyformatsupportedbyGecko(e.g.PNG,GIForJPEGformat).Othercanvaselementsonthesamepagecanalsobeusedasthesource.
Canvas相称风趣的一项功效就是能够引进图象,它能够用于图片分解大概制造背景等。而今朝仅能够在图象中到场笔墨(尺度申明中并没有包括绘制笔墨的功效)。只需是Gecko撑持的图象(如PNG,GIF,JPEG等)都能够引进到canvas中,并且别的的canvas元素也能够作为图象的来历。
引进图象Importingimages
Importingimagesisbasicallyatwostepprocess:
引进图象只必要复杂的两步:
- FirstlyweneedareferencetoaJavaScriptImageobjectorothercanvaselementasasource.ItisntpossibletouseimagesbysimplyprovidingaURL/pathtothem.
- SecondlywedrawtheimageonthecanvasusingthedrawImagefunction.
- 第一固然是来历图片,不是复杂的URL路径,但能够是一个JavaScript的Image工具援用,又大概别的的canvas元素。
- 然后用drawImage办法将图象拔出到canvas中。
Letslookatsteponefirst.Therearebasicallyfouroptionsavailable:
先来看看第一步,基础上有四种可选体例:
援用页面内的图片Usingimageswhichareonthesamepage
Wecanaccessallimagesonapagebyusingeitherthedocument.imagescollection,thedocument.getElementsByTagNamemethod,orifweknowtheIDattributeoftheimage,thedocument.getElementByIdmethod.
我们能够经由过程document.images汇合、document.getElementsByTagName办法又大概document.getElementById办法来猎取页面内的图片(假如已知图片元素的ID。
利用别的canvas元素Usingothercanvaselements
Justaswithnormalimagesweaccessothercanvaselementsusingeitherthedocument.getElementsByTagNamemethodorthedocument.getElementByIdmethod.Makesureyouvedrawnsomethingtothesourcecanvasbeforeusingitinyourtargetcanvas.
和援用页面内的图片相似地,用document.getElementsByTagName或document.getElementById办法来猎取别的canvas元素。但你引进的应当是已筹办好的canvas。
Oneofthemorepracticalusesofthiswouldbetouseasecondcanvaselementasathumbnailviewoftheotherlargercanvas.
一个经常使用的使用就是为另外一个年夜的canvas做缩略图。
<由零入手下手创立图象Creatinganimagefromscratch
AnotheroptionistocreatenewImageobjectsinourscript.Themaindisadvantageofthisapproachisthatifwedontwantourscripttohaltinthemiddlebecauseitneedstowaitforanimagetoload,weneedsomeformofimagepreloading.
别的,我们能够用剧本创立一个新的Image工具,但这类办法的次要弱点是假如不但愿剧本由于守候图片安装而停息,还得必要冲破预装载。
Basicallytocreateanewimageobjectwedothis:
我们能够经由过程上面复杂的办法来创立图片:
- varimg=newImage();//CreatenewImageobject
- img.src=myImage.png;//Setsourcepath
- varimg=newImage();//CreatenewImageobjectimg.src=myImage.png;//Setsourcepath
复制代码 Whenthisscriptgetsexecuted,theimagestartsloading.IfloadingisntfinishedwhenadrawImagestatementgetsexecuted,thescripthaltsuntiltheimageisfinishedloading.Ifyoudontwantthistohappen,useanonloadeventhandler:
当剧本实行后,图片入手下手装载。若挪用drawImage时,图片没装载完,剧本会守候直至装载终了。假如不但愿如许,可使用onload事务:
- varimg=newImage();//CreatenewImageobject
- img.onload=function(){
- //executedrawImagestatementshere
- }
- img.src=myImage.png;//Setsourcepath
- varimg=newImage();//CreatenewImageobjectimg.onload=function(){//executedrawImagestatementshere}img.src=myImage.png;//Setsourcepath
复制代码 Ifyoureonlyusingoneexternalimagethiscanbeagoodapproachbutonceyouneedtotrackmorethanoneweneedtoresorttosomethingmorecunning.ItsbeyondthescopeofthistutorialtolookatimagepreloadingtacticsbutyoucancheckoutJavaScriptImagePreloaderforacompletesolution.
假如你只用到一张图片的话,这已够了。但一旦必要不止一张图片,那就必要加倍庞大的处置办法,但图片预装载战略超越本教程的局限,感乐趣的话能够参考JavaScriptImagePreloader。
经由过程data:url体例嵌进图象Embeddinganimageviadata:url
Anotherpossiblewaytoincludeimagesisviathedata:url.DataurlsallowyoutocompletelydefineanimageasaBase64encodedstringofcharactersdirectlyinyourcode.Oneadvantageofdataurlsisthattheresultingimageisavailableimmediatelywithoutanotherroundtriptotheserver.(AnotheradvantageisthatitisthenpossibletoencapsulateinonefileallofyourCSS,Javascript,HTML,andimages,makingitmoreportabletootherlocations.)Somedisadvantagesofthismethodarethatyourimageisnotcached,andforlargerimagestheencodedurlcanbecomequitelong:
我们还能够经由过程data:url体例来援用图象。Dataurls同意用一串Base64编码的字符串的体例来界说一个图片。其长处就是图片内容立即可用,不必再到服务器兜一圈。(另有一个长处是,能够将CSS,JavaScript,HTML和图片全体封装在一同,迁徙起来非常便利。)弱点就是图象没法缓存,图片年夜的话内嵌的url数据会相称的长:
- varimg_src=data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==;
- varimg_src=data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==;
复制代码 drawImage
OncewehaveareferencetooursourceimageobjectwecanusethedrawImagemethodtorenderittothecanvas.AswewellseelaterthedrawImagemethodisoverloadedandhasthreedifferentvariants.Initsmostbasicformitlookslikethis.
一旦取得了源图工具,我们就能够利用drawImage办法将它衬着到canvas里。drawImage办法有三种形状,上面是最基本的一种。
drawImage(image,x,y)
Whereimageisareferencetoourimageorcanvasobject.xandyformthecoordinateonthetargetcanvaswhereourimageshouldbeplaced.
个中image是image大概canvas工具,x和y是其在方针canvas里的肇端坐标。
drawImage示例1
InthefollowingexampleIwillbeusinganexternalimageasthebackdropofasmalllinegraph.Usingbackdropscanmakeyourscriptconsiderablysmallerbecausewedontneedtodrawanelaboratebackground.ImonlyusingoneimageheresoIusetheimageobjectsonloadeventhandlertoexecutethedrawingstatements.ThedrawImagemethodplacesthebackdroponthecoordinate(0,0)whichisthetopleftcornerofthecanvas.
上面一个例子我用一个内部图象作为一线性图的背景。用背景图我们就不必要绘制卖力的背景,省下很多代码。这里只用到一个image工具,因而就在它的onload事务呼应函数中触发绘制举措。drawImage办法将背景图安排在canvas的左上角(0,0)处。
functiondraw(){
- varctx=document.getElementById(canvas).getContext(2d);
- varimg=newImage();
- img.onload=function(){
- ctx.drawImage(img,0,0);
- ctx.beginPath();
- ctx.moveTo(30,96);
- ctx.lineTo(70,66);
- ctx.lineTo(103,76);
- ctx.lineTo(170,15);
- ctx.stroke();
- }
- img.src=images/backdrop.png;
- }
- functiondraw(){varctx=document.getElementById(canvas).getContext(2d);varimg=newImage();img.onload=function(){ctx.drawImage(img,0,0);ctx.beginPath();ctx.moveTo(30,96);ctx.lineTo(70,66);ctx.lineTo(103,76);ctx.lineTo(170,15);ctx.stroke();}img.src=images/backdrop.png;}
复制代码 缩放Scaling
ThesecondvariantofthedrawImagemethodaddstwonewparametersanditallowsustoplacescaledimagesonthecanvas.
drawImage办法的又一变种是增添了两个用于把持图象在canvas中缩放的参数。
drawImage(image,x,y,width,height)
Wherewidthandheightistheimagessizeonthetargetcanvas.傍边width和height分离是图象在canvas中显现巨细。
drawImage示例2
InthisexampleImgoingtouseanimageasawallpaperandrepeatitseveraltimesonthecanvas.Thisisdonesimplybyloopingandplacingthescaledimagesatdifferentpositions.Inthecodebelowthefirstforloopsthroughtherowsthesecondforloopthecolumns.Theimageisscaledonethirdofitsoriginalsizewhichis50x38pixels.Wellseehowthiscouldalsohavebeenachieved,bycreatingacustompattern,laterinthistutorial.
在这个例子里,我会用一张图片像背景一样在canvas中以反复平放开来。完成起来也很复杂,只必要轮回放开经由缩放的图片便可。见上面的代码,第一层for轮回是做行反复,第二层是做列反复的。图象巨细被缩放至本来的三分之一,50x38px。这类办法能够用来很好的到达背景图案的效果,鄙人面的教程中会看到。
Note:Imagescanbecomeblurrywhenscalinguporgrainyiftheyrescaleddowntoomuch.Scalingisprobablybestnotdoneifyouvegotsometextinitwhichneedstoremainlegible.
注重:图象大概会由于年夜幅度的缩放而变得起杂点大概含混。假如您的图象内里有笔墨,那末最好仍是不要举行缩放,由于那样处置以后极可能图象里的笔墨就会变得没法识别了。
functiondraw(){
- varctx=document.getElementById(canvas).getContext(2d);
- varimg=newImage();
- img.onload=function(){
- for(i=0;i<4;i++){
- for(j=0;j<3;j++){
- ctx.drawImage(img,j*50,i*38,50,38);
- }
- }
- }
- img.src=images/rhino.jpg;
- }
- functiondraw(){varctx=document.getElementById(canvas).getContext(2d);varimg=newImage();img.onload=function(){for(i=0;i<4;i++){for(j=0;j<3;j++){ctx.drawImage(img,j*50,i*38,50,38);}}}img.src=images/rhino.jpg;}
复制代码 切片Slicing
ThethirdandlastvariantofthedrawImagemethodhaseightnewparameters.Wecanusethismethodtoslicepartsofasourceimageanddrawthemtothecanvas.
drawImage办法的第三个也是最初一个变种有8个新参数,用于把持做切片显现的。
drawImage(image,sx,sy,sWidth,sHeight,dx,dy,dWidth,dHeight)
Thefirstparameterimage,justaswiththeothervariants,iseitherareferencetoanimageobjectorareferencetoadifferentcanvaselement.Fortheothereightparametesitsbesttolookattheimageontheright.Thefirstfourparametersdefinethelocationandsizeofthesliceonthesourceimage.Thelastfourparametersdefinethepositionandsizeonthedestinationcanvas.
第一个参数和别的的是不异的,都是一个图象大概另外一个canvas的援用。别的8个参数最好是参照右侧的图解,前4个是界说图象源的切片地位和巨细,后4个则是界说切片的方针显现地位和巨细。
Slicingcanbeausefultoolwhenyouwanttomakecompositions.Youcouldhaveallelementsinasingleimagefileandusethismethodtocompositeacompletedrawing.Forinstance,ifyouwanttomakeachartyoucouldhaveaPNGimagecontainingallthenecessarytextinasinglefileanddependingonyourdatacouldchangethescaleofyourchartwithoutverymuchdiffculty.Anotheradvantageisthatyoudontneedtoloadeveryimageindividually.
切片是个做图象分解的壮大工具。假定有一张包括了一切元素的图象,那末你能够用这个办法来分解一个完全图象。比方,你想画一张图表,而手上有一个包括一切必须的笔墨的PNG文件,那末你能够很容易的依据实践数据的必要来改动终极显现的图表。这办法的另外一个优点就是你不必要独自装载每个图象。
drawImage示例3
InthisexampleImgoingtousethesamerhinoasweveseenabove,butnowImgoingtosliceitsheadoutandcompositeitintoapictureframe.Theimageofthepictureframeincludesadropshadowwhichhasbeensavedasa24-bitPNGimage.Because24-bitPNGimagesincludeafull8-bitalphachannel,unlikeGIFand8-bitPNGimages,Icanplaceitontoanybackgroundanddonthavetoworryaboutamattecolor.
在这个例子内里我用到下面已用过的犀牛图象,不外此次我要给犀牛头做个切片特写,然后分解到一个相框内里往。相框带有暗影效果,是一个以24-bitPNG格局保留的图象。由于24-bitPNG图象带有一个完全的8-bitalpha通道,与GIF和8-bitPNG分歧,我能够将它放成背景而不用忧虑底色的成绩。
Itookadifferentapproachtotheloadingoftheimagesthantheexampleabove.IjustplacedtheimagesdirectlyinmyHTMLdocumentandusedaCSSruletohidethemfromview(display:none).Iassignedbothimagesanidattributetomakethemeasiertoselect.Thescriptitselfisverysimple.Ifirstdrawtheslicedandscaledimageonthecanvas(firstdrawImagestatement),andthenplacetheframeontop(seconddrawImagestatement).
我用一个与下面用到的分歧的办法来装载图象,间接将图象拔出到HTML内里,然后经由过程CSS埋没(display:none)它。两个图象我都赋了id,便利前面利用。看上面的剧本,相称复杂,起首对犀牛头做好切片(第一个drawImage)放在canvas上,然后再下面套个相框(第二个drawImage)。
- functiondraw(){
- varcanvas=document.getElementById(canvas);
- varctx=canvas.getContext(2d);
- //Drawslice
- ctx.drawImage(document.getElementById(source),
- 33,71,104,124,21,20,87,104);
- //Drawframe
- ctx.drawImage(document.getElementById(frame),0,0);
- }
- functiondraw(){varcanvas=document.getElementById(canvas);varctx=canvas.getContext(2d);//Drawslicectx.drawImage(document.getElementById(source),33,71,104,124,21,20,87,104);//Drawframectx.drawImage(document.getElementById(frame),0,0);}
复制代码 Artgalleryexample
InthefinalexampleofthischapterIvemadealittleartgallery.Thegalleryconsistsofatablecontainingseveralimages.Whenthepageisloaded,foreachimageinthepageacanvaselementisinsertedandaframeisdrawnarroundit.
Inmycase,allimageshaveafixedwidthandheight,andsodoestheframethatsdrawnaroundit.Youcouldenhancethescriptsothatitusestheimageswidthandheighttomaketheframefitperfectlyaroundit.
Thecodebelowshouldbeself-explanatory.Weloopthroughtheimagesarrayandaddnewcanvaselementsaccordingly.Probablytheonlythingtonote,forthosenotsofamilarwiththeDOM,istheuseoftheinsertBeforemethod.insertBeforeisamethodoftheparentnode(atablecell)oftheelement(theimage)beforewhichwewanttoinsertournewnode(thecanvaselement).
- functiondraw(){
- //Loopthroughallimages
- for(i=0;i<document.images.length;i++){
- //Dontaddacanvasfortheframeimage
- if(document.images.getAttribute(id)!=frame){
- //Createcanvaselement
- canvas=document.createElement(CANVAS);
- canvas.setAttribute(width,132);
- canvas.setAttribute(height,150);
- //Insertbeforetheimage
- document.images.parentNode.insertBefore(canvas,document.images);
- ctx=canvas.getContext(2d);
- //Drawimagetocanvas
- ctx.drawImage(document.images,15,20);
- //Addframe
- ctx.drawImage(document.getElementById(frame),0,0);
- }
- }
- }
</p>
WHATWG版和W3C版的HTML5规范虽然根源相同,在一些领域却已经产生分歧。 |
|