Foreword... xv
AbouttheAuthors... xvi
AbouttheTechnicalReviewer ... xvii
Acknowledgments ... xviii
Introduction ... xix
Chapter1:OverviewofHTML5...1
Chapter2:UsingtheCanvasAPI ...23
Chapter3:WorkingwithScalableVectorGraphics...63
Chapter4:WorkingwithAudioandVideo ...83
Chapter5:UsingtheGeolocationAPI ...107
Chapter6:UsingtheCommunicationAPIs ...135
Chapter7:UsingtheWebSocketAPI ...159
Chapter8:UsingtheFormsAPI...193
Chapter9:WorkingwithDrag-and-Drop ...217
Chapter10:UsingtheWebWorkersAPI...241
Chapter11:UsingtheStorageAPIs...263
Chapter12:CreatingOfflineWebApplications...295
Chapter13:TheFutureofHTML5 ...313
Overview of HTML5
ThisbookisaboutHTML5Programming.BeforeyoucanunderstandHTML5programming,however, youneedtotakeastepbackandunderstandwhatHTML5is,abitofthehistorybehindit,andthe differencesbetweenHTML4andHTML5.
Inthischapter,wegetrighttothepracticalquestionstowhicheveryonewantsanswers.Why HTML5,andwhyalltheexcitementjustnow?WhatarethenewdesignprinciplesthatmakeHTML5 trulyrevolutionary—butalsohighlyaccommodating?Whataretheimplicationsofaplugin-free
paradigm;what’sinandwhat’sout?What’snewinHTML,andhowdoesthiskickoffawholenewerafor webdevelopers?Let’sgettoit.
TheStorySoFar—TheHistoryofHTML5
HTMLgoesbackalongway.ItwasfirstpublishedasanInternetdraftin1993.The’90ssawan enormousamountofactivityaroundHTML,withversion2.0,versions3.2,and4.0(inthesameyear!), andfinally,in1999,version4.01.Inthecourseofitsdevelopment,theWorldWideWebConsortium (W3C)assumedcontrolofthespecification.
Aftertherapiddeliveryofthesefourversionsthough,HTMLwaswidelyconsideredadead-end;the focusofwebstandardsshiftedtoXMLandXHTML,andHTMLwasputonthebackburner.Inthe meantime,HTMLrefusedtodie,andthemajorityofcontentonthewebcontinuedtobeservedas HTML.ToenablenewwebapplicationsandaddressHTML’sshortcomings,newfeaturesand specificationswereneededforHTML.
Wantingtotakethewebplatformtoanewlevel,asmallgroupofpeoplestartedtheWebHypertext ApplicationWorkingGroup(WHATWG)in2004.TheycreatedtheHTML5specification.Theyalsobegan workingonnewfeaturesspecificallygearedtowebapplications—theareatheyfeltwasmostlacking.It wasaroundthistimethatthetermWeb2.0wascoined.Anditreallywaslikeasecondnewweb,asstatic websitesgavewaytomoredynamicandsocialsitesthatrequiredmorefeatures—alotmorefeatures.
TheW3CbecameinvolvedwithHTMLagainin2006andpublishedthefirstworkingdraftfor HTML5in2008,andtheXHTML2workinggroupstoppedin2009.Anothertwoyearspassed,andthatis wherewestandtoday.BecauseHTML5solvesverypracticalproblems(asyouwillseelater),browser vendorsarefeverishlyimplementingitsnewfeatures,eventhoughthespecificationhasnotbeen completelylockeddown.Experimentationbythebrowsersfeedsbackintoandimprovesthe specification.HTML5israpidlyevolvingtoaddressrealandpracticalimprovementstotheweb platform.
MOMENTS IN HTML
Iauthoredmyfirsthomepagebackin1995.Atthetime,a‘homepage’wassomethingyoucreatedtotalk
aboutyourself.Itusuallyconsistedofbadlyscannedpictures,
<blink>tags,informationaboutwhereyou
livedandwhatyouwerereading,andwhichcomputer-relatedprojectyouwerecurrentlyworkingon.
thepotentialislimitless.Thoseofuswhofirstused
<img>tagsinthemid-1990sprobablyhadnoideathat
withintenyears,manypeoplewouldbestoringandeditingtheirphotosonline,butweshouldhave
thetargetdateforthecandidaterecommendation.Theseconddateis2022,whichistheproposed recommendation.Wait!Notsofast!Don’tclosethisbooktosetitasidefortenyearsbeforeyouconsiderWhoIsDevelopingHTML5?
Weallknowthatacertaindegreeofstructureisneeded,andsomebodyclearlyneedstobeinchargeof thespecificationofHTML5.Thatchallengeisthejobofthreeimportantorganizations:
• WebHypertextApplicationTechnologyWorkingGroup(WHATWG):Foundedin 2004byindividualsworkingforbrowservendorsApple,Mozilla,Google,and Opera,WHATWGdevelopsHTMLandAPIsforwebapplicationdevelopmentand providesopencollaborationofbrowservendorsandotherinterestedparties.
• WorldWideWebConsortium(W3C):TheW3CcontainstheHTMLworkinggroup thatiscurrentlychargedwithdeliveringtheirHTML5specification.
• InternetEngineeringTaskForce(IETF):Thistaskforcecontainsthegroups responsibleforInternetprotocolssuchasHTTP.HTML5definesanew WebSocketAPIthatreliesonanewWebSocketprotocol,whichisunder developmentinanIETFworkinggroup.
ANewVision
HTML5isbasedonvariousdesignprinciples,spelledoutintheWHATWGspecification,thattruly embodyanewvisionofpossibilityandpracticality.
• Compatibility • Utility
• Interoperability • Universalaccess
CompatibilityandPavingtheCowPaths
Don’tworry;HTML5isnotanupsettingkindofrevolution.Infact,oneofitscoreprinciplesistokeep everythingworkingsmoothly.IfHTML5featuresarenotsupported,thebehaviormustdegrade gracefully.Inaddition,sincethereisabout20yearsofHTMLcontentoutthere,supportingallthat existingcontentisimportant.
Alotofefforthasbeenputintoresearchingcommonbehavior.Forexample,Googleanalyzed millionsofpagestodiscoverthecommonIDandClassnamesforDIVtagsandfoundahugeamountof repetition.Forexample,manypeopleusedDIV id="header"tomarkupheadercontent.HTML5isall aboutsolvingrealproblems,right?Sowhynotsimplycreatea<header>element?
AlthoughsomefeaturesoftheHTML5standardarequiterevolutionary,thenameofthegameis evolutionnotrevolution.Afterall,whyreinventthewheel?(Or,ifyoumust,thenatleastmakeabetter one!)
UtilityandthePriorityofConstituencies
TheHTML5specificationiswrittenbaseduponadefinitePriorityofConstituencies.Andasprioritiesgo, “theuserisking.”Thismeans,whenindoubt,thespecificationvaluesusersoverauthors,over
Considerthisexample.ThefollowingcodesnippetsareallequallyvalidinHTML5:
id="prohtml5" id=prohtml5 ID="prohtml5"
Sure,somewillobjecttothisrelaxedsyntax,butthebottomlineisthattheenduserdoesn’treally care.We’renotsuggestingthatyoustartwritingsloppycode,butultimately,it’stheenduserwhosuffers whenanyoftheprecedingexamplesgenerateserrorsanddoesn’trendertherestofthepage.
HTML5hasalsospawnedthecreationofXHTML5toenableXMLtoolchainstogeneratevalid HTML5code.TheserializationsoftheHTMLortheXHTMLversionshouldproducethesameDOM treeswithminimaldifferences.Obviously,theXHTMLsyntaxisalotstricter,andthecodeinthelasttwo exampleswouldnotbevalid.
SecurebyDesign
AlotofemphasishasbeengiventomakingHTML5securerightoutofthestartinggate.Eachpartofthe specificationhassectionsonsecurityconsiderations,andsecurityhasbeenconsideredupfront.HTML5 introducesaneworigin-basedsecuritymodelthatisnotonlyeasytousebutisalsousedconsistentlyby differentAPIs.Thissecuritymodelallowsustodothingsinwaysthatusedtobeimpossible.For example,itallowsustocommunicatesecurelyacrossdomainswithouthavingtoreverttoallkindsof clever,creative,butultimatelyNon-securehacks.Inthatrespect,wedefinitelywillnotbelookingback tothegoodolddays.
SeparationofPresentationandContent
HTML5takesagiantsteptowardthecleanseparationofpresentationandcontent.HTML5strivesto createthisseparationwhereverpossible,anditdoessousingCSS.Infact,mostofthepresentational featuresofearlierversionsofHTMLarenolongersupported,butwillstillwork,thankstothe
compatibilitydesignprinciplementionedearlier.Thisideaisnotentirelynew,though;itwasalreadyin theworksinHTML4TransitionalandXHTML1.1.Webdesignershavebeenusingthisasabestpractice foralongtime,butnow,itisevenmoreimportanttocleanlyseparatethetwo.Theproblemswith presentationalmarkupare:
• Pooraccessibility
• Unnecessarycomplexity(it’shardertoreadyourcodewithalltheinlinestyling) • Largerdocumentsize(duetorepetitionofstylecontent),whichtranslatesinto
slower-loadingpages
InteroperabilitySimplification
HTML5isallaboutsimplificationandavoidingneedlesscomplexity.TheHTML5mantra?“Simpleis better.Simplifywhereverpossible.”Herearesomeexamplesofthis:
• NativebrowserabilityinsteadofcomplexJavaScriptcode • Anew,simplifiedDOCTYPE
• PowerfulyetsimpleHTML5APIs
• Accessibility:Tosupportuserswithdisabilities,HTML5workscloselywitha relatedstandardcalledWebAccessibilityInitiative(WAI)AccessibleRichInternet Applications(ARIA).WAI-ARIAroles,whicharesupportedbyscreenreaders,can bealreadybeaddedtoyourHTMLelements.
• MediaIndependence:HTML5functionalityshouldworkacrossalldifferentdevices andplatformsifatallpossible.
containedrenderingmodelthatisdifferentfromthatofthebasewebpage,developersfacedifficultiesif pop-upmenusorothervisualelementsneedtocrossthepluginboundariesonapage.Thisiswhere HTML5comesonthescene,smiles,andwavesitsmagicwandofnativefunctionality.Youcanstyle elementswithCSSandscriptwithJavaScript.Infact,thisiswhereHTML5flexesitsbiggestmuscle, anativecodehastoofferoveraplugin.Infact,virtuallyeverythingbecomeseasierwhenyou’renot workingwithablackbox.Whatthisalladdsuptoisatrulypowerfulnewmedium,whichiswhywe decidedtowriteabookaboutHTML5programming,andnotjustaboutthenewelements!
What’sInandWhat’sOut?
• Webstorage • Indexeddatabase
• ApplicationCache(OfflineWebApps) • WebWorkers
• DragandDrop
• XMLHttpRequestLevel2
Asyoucansee,alotoftheAPIswecoverinthisbookareonthislist.HowdidwechoosewhichAPIs tocover?Wechosetocoverfeaturesthatwereatleastsomewhatbaked.Translation?They’reavailablein someforminmorethanonebrowser.Other(less-baked)featuresmayonlyworkinonespecialbeta versionofabrowser,whileothersarestilljustideasatthispoint.
Asfarasbrowsersupportgoes,therearesomeexcellentonlineresourcesthatyoucanusetocheck current(andfuture)browsersupport.Thesitewww.caniuse.comprovidesanexhaustivelistoffeatures andbrowsersupportbrokendownbybrowserversionandthesitewww.html5test.com checksthe supportforHTML5featuresinthebrowseryouusetoaccessit.
Furthermore,thisbookdoesnotfocusonprovidingyouwiththeemulationworkaroundstomake yourHTML5applicationsrunseamlesslyonantiquebrowsers.Instead,wewillfocusprimarilyonthe specificationofHTML5andhowtouseit.Thatsaid,foreachoftheAPIswedoprovidesomeexample codethatyoucanusetodetectitsavailability.Ratherthanusinguseragentdetection,whichisoften unreliable,weusefeaturedetection.Forthat,youcanalsouseModernizr—aJavaScriptlibrarythat providesveryadvancedHTML5andCSS3featuredetection.WehighlyrecommendyouuseModernizr inyourapplications,becauseitishands-downthebesttoolforthis.
MORE MOMENTS IN HTML
Franksays:
“Hi,I’mFrank,andIsometimespaint.
OneofthefirstHTMLcanvasdemonstrationsIsawwasabasicpaintingapplicationthatmimickedthe
userinterfaceofMicrosoftPaint.Althoughitwasdecadesbehindthestateoftheartindigitalpaintingand,
atthetime,raninonlyafractionofexistingbrowsers,itgotmethinkingaboutthepossibilitiesit
represented.
WhenIpaintdigitally,Itypicallyuselocallyinstalleddesktopsoftware.Whilesomeoftheseprogramsare
excellent,theylackthecharacteristicsthatmakewebapplicationssogreat.Inshort,theyare
disconnected.Sharingdigitalpaintingshas,todate,involvedexportinganimagefromapainting
applicationanduploadingittotheWeb.Collaborationorcritiquesonalivecanvasareoutofthequestion.
HTML5applicationscanshort-circuittheexportcycleandmakethecreativeprocessfitintotheonline
worldalongwithfinishedimages.
Wecannowbuildgreatsoftwaretocreateandenjoyimages,music,movies,andmore.Evenbetter,the
softwarewemakewillbeonandofftheWeb:aplatformthatisubiquitous,empowering,andonline.”
What’sNewinHTML5?
BeforewestartprogrammingHTML5,let’stakeaquicklookatwhat’snewinHTML5.
NewDOCTYPEandCharacterSet
Firstofall,theDOCTYPEforwebpageshasbeengreatlysimplified.Compare,forexample,thefollowing HTML4DOCTYPEs:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
Whocouldeverrememberanyofthese?Wecertainlycouldn’t.Wewouldalwaysjustcopyandpaste somelengthyDOCTYPEintothepage,alwayswithaworryinthebackofourminds,“Areyouabsolutely sureyoupastedtherightone?”HTML5neatlysolvesthisproblemasfollows:
<!DOCTYPE html>
Nowthat’saDOCTYPEyoumightjustremember.LikethenewDOCTYPE,thecharactersetdeclaration hasalsobeenabbreviated.Itusedtobe
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Now,itis:
<meta charset="utf-8">
Youcanevenleaveoffthequotationmarksaround“utf-8”ifyouwantto.UsingthenewDOCTYPE triggersthebrowsertodisplaypagesinstandardsmode.Forexample,Figure1-1showstheinformation youwillseeifyouopenanHTML5pageinFirefox,andyouclickTools➤PageInfo.Inthisexample,the
Figure1-1.Apagerenderedinstandards-compliantmode
WhenyouusethenewHTML5DOCTYPE ,ittriggersbrowserstorenderthepageinstandards-compliantmode.Asyoumayknow,Webpagescanhavedifferentrenderingmodes,suchasQuirks, AlmostStandards,andStandards(orno-quirks)mode.TheDOCTYPEindicatestothebrowserwhich modetouseandwhatrulesareusedtovalidateyourpages.InQuirksmode,browserstrytoavoid breakingpagesandrenderthemeveniftheyarenotentirelyvalid.HTML5introducesnewelementsand hasmarkedothersasobsolete(moreonthisinthenextsection).Ifyouusetheseobsoleteelements, yourpagewillnotbevalid.However,browserswillcontinuetorenderthemastheyusedto.
NewandDeprecatedElements
HTML5introducesmanynewmarkupelements,whichitgroupsintosevendifferentcontenttypes. TheseareshownbelowinTable1-1.
Table1-1.HTML5ContentTypes
ContentType Description
Embedded Contentthatimportsotherresourcesintothedocument,forexampleaudio,video,
canvas,andiframe
Flow Elementsusedinthebodyofdocumentsandapplications,forexampleform,h1,and
Heading Sectionheaders,forexampleh1,h2,andhgroup
Interactive Contentthatusersinteractwith,forexampleaudioorvideo controls,button,and
textarea
Metadata Elements—commonlyfoundintheheadsection—thatsetupthepresentationor behavioroftherestofthedocument,forexamplescript,style,andtitle Phrasing Textandtextmarkupelements,forexamplemark,kbd,sub,andsup
Sectioning Elementsthatdefinesectionsinthedocument,forexamplearticle,aside,andtitle
MostoftheseelementscanbestyledwithCSS.Inaddition,someofthem,suchascanvas,audio, andvideo,canbeusedbythemselves,thoughtheyareaccompaniedbyAPIsthatallowforfine-grained nativeprogrammaticcontrol.TheseAPIswillbediscussedinmuchmoredetaillaterinthisbook.
Itisbeyondthescopeofthisbooktodiscussallthesenewelements,butmostofthesectioning elements(discussedinthenextsection)arenew.Thecanvas,audio,andvideoelementsarealsonewin HTML5.
Likewise,we’renotgoingtoprovideanexhaustivelistofallthedeprecatedtags(therearemany goodonlineresourcesonlineforthis),butmanyoftheelementsthatperformedinlinestylinghavebeen markedasobsoleteinfavorofusingCSS,suchasbig,center,font,andbasefont.
SemanticMarkup
OnecontenttypethatcontainsmanynewHTML5elementsisthesectioningcontenttype.HTML5 definesanewsemanticmarkuptodescribeanelement’scontent.Usingsemanticmarkupdoesn’t provideanyimmediatebenefitstotheenduser,butitdoessimplifythedesignofyourHTMLpages. What’smore,itwillmakeyourpagesmoremachine-readableandaccessible.Forexample,searchand syndicationengineswilldefinitelybetakingadvantageoftheseelementsastheycrawlandindexpages.
Aswesaidbefore,HTML5isallaboutpavingthecowpaths.GoogleandOperaanalyzedmillionsof pagestodiscoverthecommonIDnamesforDIVtagsandfoundahugeamountofrepetition.For example,sincemanypeopleusedDIV id="footer"tomarkupfootercontent,HTML5providesasetof newsectioningelementsthatyoucanuseinmodernbrowsersrightnow.Table1-2showsthedifferent semanticmarkupelements.
Table1-2.NewSectioningHTML5Elements
SectioningElement Description
header Headercontent(forapageorasectionofthepage)
footer Footercontent(forapageorasectionofthepage)
section Asectioninawebpage
aside Relatedcontentorpullquotes
nav Navigationalaids
AlloftheseelementscanbestyledwithCSS.Infact,aswedescribedintheutilitydesignprinciple earlier,HTML5pushestheseparationofcontentandpresentation,soyouhavetostyleyourpageusing CSSstylesinHTML5.Listing1-1showswhatanHTML5pagemightlooklike.ItusesthenewDOCTYPE, characterset,andsemanticmarkupelements—inshort,thenewsectioningcontent.Thecodefile (sample.html)isavailableinthecode/introfolder.
Listing1-1.AnExampleHTML5Page
<!DOCTYPE html> <html>
<head>
<meta charset="utf-8" > <title>HTML5</title>
<link rel="stylesheet" href="html5.css"> </head>
<article>
<p>HTML5: "Lorem ipsum dolor nunc aut nunquam sit amet, consectetur adipiscing elit. Vivamus at est eros, vel fringilla urna. Pellentesque odio canbeusedtostylethecontent.Thecodefile(html5.css)isavailableinthecode/introfolder.Thisstyle sheetusessomeofthenewCSS3features,suchasroundedcorners(border-radius)androtate
transformations(transform: rotate();).CSS3—justlikeHTML5itself—isstillunderdevelopment,and itismodularizedwithsubspecificationsforeasierbrowseruptake(forexample,transformation, animation,andtransitionareallareasthatareinseparatesubspecifications).
ExperimentalCSS3featuresareprefixedwithvendorstringstoavoidnamespaceconflictsshould thespecificationschange.Todisplayroundedcorners,gradients,shadows,andtransformations,itis currentlynecessarytouseprefixessuchas-moz-(forMozilla),o-(forOpera),-webkit- (forWebKit-basedbrowserssuchasSafariandChrome),and-ms-(forInternetExplorer)inyourdeclarations. Listing1-2.CSSFilefortheHTML5Page
body {
background-color:#CCCCCC;
}
nav a:link, nav a:visited { display: block;
border-bottom: 3px solid #fff; padding: 10px;
margin: 5px;
#container {
background-color: #888;
article header {
-webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; padding: 5px; }
article footer {
article h1 {
font-size: 18px; }
aside {
display:block; width:25%; float:left; }
aside h3 {
margin: 15px; color: white; }
aside p {
margin: 15px; color: white; font-weight: bold; font-style: italic; }
footer {
clear: both; display: block;
background-color: #F47D31; color:#FFFFFF;
text-align:center; padding: 15px; }
footer h2 {
font-size: 14px; color: white; }
/* links */ a {
color: #F47D31; }
a:hover {
Figure1-2showsanexampleofthepageinListing1-1,styledwithCSS(andsomeCSS3)styles.Keep inmind,however,thatthereisnosuchthingasatypicalHTML5page.Anythinggoes,really,andthis exampleusesmanyofthenewtagsmainlyforpurposesofdemonstration.
Figure1-2.AnHTML5pagewithallthenewsemanticmarkupelements
Onelastthingtokeepinmindisthatbrowsersmayseemtorenderthingsasiftheyactually understandthesenewelements.Thetruthis,however,thattheseelementscouldhavebeenrenamed
SimplifyingSelectionUsingtheSelectorsAPI
getElementById() Returnstheelementwiththe
specifiedidattributevalue <div id="foo">
getElementById("foo");
getElementsByName() Returnsallelementswhosename attributehasthespecifiedvalue
<input type="text" name="foo"> getElementsByName("foo");
getElementsByTagName() Returnallelementswhosetagname
matchesthespecifiedvalue <input type="text"> getElementsByTagName("input");
FunctionDescription Example Result
querySelector() Returnthefirst elementinthepage whichmatchesthe specifiedselector rules(s)
document.querySelector("input.error"); Returnthe firstinput fieldwitha styleclassof “error”
querySelectorAll() Returnsall elementswhich matchthespecified ruleorrules
document.querySelectorAll("#results
td"); Returnanytablecells insidethe elementwith
idresults
ItisalsopossibletosendmorethanoneselectorruletotheSelectorAPIfunctions,forexample:
InthecaseofquerySelector(),thefirstelementthatmatcheseitherruleisselected.Inthecaseof forthis(querySelector.htmland querySelectorAll.html)arelocatedinthecode/introdirectory. Listing1-3.UsingtheSelectorAPI
<!DOCTYPE html> <html>
<head>
<meta charset="utf-8" />
<title>Query Selector Demo</title> <style type="text/css">
td {
<td>A1</td> <td>A2</td> <td>A3</td> </tr>
<tr>
<td>B1</td> <td>B2</td> <td>B3</td> </tr>
<tr>
<td>C1</td> <td>C2</td> <td>C3</td> </tr>
</table>
<button type="button" id="findHover" autofocus>Find 'td:hover' target</button> <div id="hoverResult"></div>
<script type="text/javascript">
document.getElementById("findHover").onclick = function() { // find the table cell currently hovered in the page var hovered = document.querySelector("td:hover"); if (hovered)
document.getElementById("hoverResult").innerHTML = hovered.innerHTML; }
</script> </section> </body> </html>
Asyoucanseefromthisexample,findingtheelementauserishoveringoverisaone-lineexercise using:
var hovered = document.querySelector("td:hover");
■
Note
NotonlyaretheSelectorAPIshandy,buttheyareoftenfasterthantraversingtheDOMusingthelegacy
childretrievalAPIs.Browsersarehighlyoptimizedforselectormatchinginordertoimplementfaststylesheets.
Itshouldnotbetoosurprisingtofindthattheformalspecificationofselectorsisseparatedfromthe specificationforCSSattheW3C.Asyou’veseenhere,selectorsaregenerallyusefuloutsideofstyling. Thefulldetailsofthenewselectorsareoutsidethescopeofthisbook,butifyouareadeveloperseeking theoptimalwaystomanipulateyourDOM,youareencouragedtousethenewSelectorsAPItorapidly navigateyourapplicationstructure.
JavaScriptLoggingandDebugging
Thoughthey’renottechnicallyafeatureofHTML5,JavaScriptloggingandin-browserdebuggingtools havebeenimprovedgreatlyoverthepastfewyears.Thefirstgreattoolforanalyzingwebpagesandthe coderunninginthemwastheFirefoxadd-on,Firebug.
Figure1-3.DeveloperToolsviewinChrome
Manyofthedebuggingtoolsofferawaytosetbreakpointstohaltcodeexecutionandanalyzethe stateoftheprogramandthecurrentstateofthevariables.Theconsole.logAPIhasbecomethedefacto loggingstandardforJavaScriptdevelopers.Manybrowsersofferasplit-paneviewthatallowsyoutosee messagesloggedtotheconsole.Usingconsole.logismuchbetterthanmakingacalltoalert(),sinceit doesnothaltprogramexecution.
window.JSON
JSONisarelativelynewandincreasinglypopularwaytorepresentdata.ItisasubsetofJavaScriptsyntax thatrepresentsdataasobjectliterals.DuetoitssimplicityandnaturalfitinJavaScriptprogramming, JSONhasbecomethedefactostandardfordatainterchangeinHTML5applications.ThecanonicalAPI forJSONhastwofunctions,parse()andstringify()(meaningserializeorconverttostring).
TouseJSONinolderbrowsers,youneedaJavaScriptlibrary(severalcanbefoundat
http://json.org).ParsingandserializinginJavaScriptarenotalwaysasfastasyouwouldlike,soto speedupthings,newerbrowsersnowhaveanativeimplementationofJSONthatcanbecalledfrom JavaScript.ThenativeJSONobjectisspecifiedaspartoftheECMAScript5standardcoveringthenext generationoftheJavaScriptlanguage.ItisoneofthefirstpartsofECMAScript5tobewidely
DOMLevel3
Oneofthemostmalignedpartsofwebapplicationdevelopmenthasbeeneventhandling.Whilemost browserssupportstandardAPIsforeventsandelements,InternetExplorerdiffers.Earlyon,Internet Explorerimplementedaneventmodelthatdifferedfromtheeventualstandard.InternetExplorer9(IE9) nowsupportsDOMLevel2and3features,soyoucanfinallyusethesamecodeforDOMmanipulation andeventhandlinginallHTML5browsers.Thisincludestheever-importantaddEventListener()and
dispatchEvent()methods.
BrowserEngine Name Notes
AppleSafari Nitro(otherwiseknow
asSquirrelFishExtreme) ReleasedinSafari4andrefinedinversion5,itintroducesbytecodeoptimizationsanda context-threadednativecompiler.
Google
Chrome V8 SinceChrome2,itusesgenerationalgarbagecollectionforhighmemoryscalabilitywithoutinterruptions.
Microsoft
MozillaFirefox JägerMonkey Refinedfromversion3.5,thiscombinesfastinterpretation withnativecompilationfromtracetrees.
Allinall,thishealthycompetitionamongbrowservendorsisbringingtheperformanceofJavaScript everclosertothatofnativedesktopapplicationcode.
STILL MORE MOMENTS IN HTML
Petersays
:“Speakingofcompetition,andspeedyoddities,mynameisPeterandrunningismything—a
lotofrunning.
Ultrarunningisagreatsportwhereyoumeetgreatpeople.Whilerunningthelastmilesofa100-milerace
ora165-miletrailrun,youreallygettoknowpeopleinaverynewway.Atthatpoint,you’rereally
strippeddowntoyouressence,theplacewheregreatfriendshipscanhappen.There’sstilltheelementof
competition,tobesure,butmostofallthere’sadeepsenseofcamaraderie.ButIdigresshere.
TokeeptrackofhowmyfriendsaredoinginracesthatIcan’tattend(forexample,whenIamwritingan
HTML5book),Iusuallyfollowalongontheracewebsites.Notsurprisingly,the‘livetracking’optionsare
oftenquiteunreliable.
Afewyearsago,IstumbleduponasiteforaEuropeanracethathadalltherightideas.TheygaveGPS
trackerstothefrontrunnersandthendisplayedtheseracersonamap(we’llbuildsomesimilar
demonstrationsinthisbookusingGeolocationandWebSocket).Despitethefactthatitwasquitea
primitiveimplementation(usershadtoactuallyclick“refreshthepage”toseeupdates!),Icouldinstantly
seetheincrediblepotential.
Now,justafewyearslater,HTML5providesuswithtoolstobuildthesesortsofliveracetrackingwebsites
withAPIssuchasGeolocationforlocation-awareapplicationsandWebSocketsforreal-timeupdates.
There’snodoubtinmymind—HTML5hascrossedthefinishlineawinner!”
Summary
Inthischapter,wehavegivenyouageneraloverviewoftheessentialsofHTML5.
Wechartedthehistoryofitsdevelopmentandsomeoftheimportantdatescomingup.Wealso outlinedthefournewdesignprinciplesbehindtheHTML5erathatisnowdawning:compatibility, utility,interoperability,anduniversalaccess.Eachoneoftheseprinciplesopensthedoortoaworldof possibilitiesandclosesthedooronahostofpracticesandconventionsthatarenowrenderedobsolete. WethenintroducedHTML5’sstartlingnewplugin-freeparadigm,andwereviewedwhat’snewin HTML5,suchasanewDOCTYPEandcharacterset,lotsofnewmarkupelements,andwediscussedthe raceforJavaScriptsupremacy.
Inthenextchapter,we’llbeginbyexploringtheprogrammingsideofHTML5,startingwiththe CanvasAPI.
Using the Canvas API
Inthischapter,we’llexplorewhatyoucandowiththeCanvasAPI—acoolAPIthatenablesyouto dynamicallygenerateandrendergraphics,charts,images,andanimation.We’llwalkyouthroughusing thebasicsoftherenderingAPItocreateadrawingthatcanscaleandadjusttothebrowserenvironment. We’llshowyouhowtocreatedynamicpicturesbasedonuserinputinaheatmapdisplay.Ofcourse, we’llalsoalertyoutothepitfallsofusingCanvasandsharetrickstoovercomethem.
Thischapterpresumesonlyaminimalamountofgraphicsexpertise,sodon’tbeafraidtojumpin andtryoutoneofthemostpowerfulfeaturesofHTML5.
OverviewofHTML5Canvas
AnentirebookcouldbewrittenabouttheuseoftheCanvasAPI(anditwouldn’tbeasmallbook). Becausewehaveonlyachapter,we’regoingtocover(whatwethinkis)themostcommonlyused functionalityinthisveryextensiveAPI.
History
ThecanvasconceptwasoriginallyintroducedbyAppletobeusedinMacOSXWebKittocreate
dashboardwidgets.Beforethearrivalofcanvas,youcouldonlyusedrawingAPIsinabrowserthrough plug-inssuchasAdobeplug-insforFlashandScalableVectorGraphics(SVG),VectorMarkupLanguage (VML)onlyinInternetExplorer,orothercleverJavaScripthacks.
Try,forexample,todrawasimplediagonallinewithoutacanvaselement—itsoundseasy,butitisa fairlycomplextaskifyoudonothaveasimpletwo-dimensionaldrawingAPIatyourdisposal.Canvas providesjustthat,andbecauseitisanextremelyusefulthingtohaveinthebrowser,itwasaddedtothe HTML5specification.
Earlyon,ApplehintedatpossiblyreservingtheintellectualpropertyrightsintheWHATWGdraftof thecanvasspecification,whichcausedconcernatthetimeamongsomefollowersofweb
standardization.Intheend,however,AppledisclosedthepatentsundertheW3C'sroyalty-freepatent licensingterms.
SVG versus Canvas
canbescaledseamlesslyatdifferentresolutionsandallowforhitdetection(knowingpreciselywherean
imageisclicked).
Whythen,wouldtheWHATWGHTML5specificationnotuseSVGexclusively?Despiteitsobvious
shortcomings,theHTML5CanvasAPIhastwothingsgoingforit:itperformswellbecauseitdoesnothave
tostoreobjectsforeveryprimitiveitdraws,anditisrelativelyeasytoimplementtheCanvasAPIbasedon
manyofthepopulartwo-dimensionaldrawingAPIsfoundinotherprogramminglanguages.Ultimately,itis
bettertohaveonebirdinthehandthantwointhebush.”
WhatIsaCanvas?
Whenyouuseacanvaselementinyourwebpage,itcreatesarectangularareaonthepage.Bydefault, thisrectangularareais300pixelswideand150pixelshigh,butyoucanspecifytheexactsizeandset otherattributesforyourcanvaselement.Listing2-1showsthemostbasiccanvaselementthatcanbe addedtoanHTMLpage.
Listing2-1.ABasicCanvasElement
<canvas></canvas>
Onceyouhaveaddedacanvaselementtoyourpage,youcanuseJavaScripttomanipulateitany wayyouwant.Youcanaddgraphics,lines,andtexttoit;youcandrawonit;andyoucanevenadd advancedanimationstoit.
TheCanvasAPIsupportsthesametwo-dimensionaldrawingoperationsthatmostmodern operatingsystemsandframeworkssupport.Ifyouhaveeverprogrammedtwo-dimensionalgraphicsin recentyears,youwillprobablyfeelrightathomewiththeCanvasAPIbecauseitisdesignedtobesimilar toexistingsystems.Ifyouhaven’t,you’reabouttodiscoverhowmuchmorepowerfularendering systemcanbethanthepreviousimagesandCSStricksdevelopershaveusedforyearstocreateweb graphics.
Toprogrammaticallyuseacanvas,youhavetofirstgetitscontext.Youcanthenperformactionson thecontextandfinallyapplythoseactionstothecontext.Youcanthinkofmakingcanvasmodifications assimilartodatabasetransactions:youstartatransaction,performcertainactions,andthencommit thetransaction.
CanvasCoordinates
Figure2-1.xandycoordinatesonacanvas
WhenNottoUseCanvas
Althoughthecanvaselementisgreatandveryuseful,youshouldnotusethecanvaselementwhen anotherelementwillsuffice.Forexample,itwouldnotbeagoodideatodynamicallydrawallthe differentheadingsforanHTMLdocumentonacanvasinsteadofsimplyusingheadingstyles(H1,H2, andsoon)thataremeantforthatpurpose.
FallbackContent
Incaseyourwebpageisaccessedbyabrowserthatdoesnotsupportthecanvaselementorasubsetof theCanvasAPIfeatures,itisagoodideatoprovideanalternatesource.Forexample,youcanprovidean alternateimageorjustsometextthatexplainswhattheusercouldbeenjoyingiftheyactuallyuseda modernbrowser.Listing2-2showshowalternatetextcanbespecifiedinsideacanvaselement.Browsers thatdonotsupportthecanvaselementwillsimplyrenderthisfallbackcontent.
Listing2-2.UseofFallbackTextInsideaCanvasElement
<canvas>
Update your browser to enjoy canvas! </canvas>
What About Canvas Accessibility?
AswithmostHTMLelements,CSScanbeappliedtothecanvaselementitselftoaddborders,padding, margins,etc.Additionally,someCSSvaluesareinheritedbythecontentsofthecanvas;fontsareagood example,asfontsdrawnintoacanvasdefaulttothesettingsofthecanvaselementitself.
willnotwinanyawardsforgraphicaldesign,itshouldservetoillustratethevariouscapabilitiesof HTML5Canvasinareasonableorder.
CheckingforBrowserSupport
Beforeyouusethecanvaselement,youwillwanttomakesurethereissupportinthebrowser.Thisway, youcanprovidesomealternatetextincasethereisnosupportintheirantiquebrowser.Listing2-3 showsonewayyoucanusetotestforbrowsersupport.
Listing2-3.CheckingforBrowserSupport
try {
document.createElement("canvas").getContext("2d"); document.getElementById("support").innerHTML = "HTML5 Canvas is supported in your browser."; } catch (e) {
document.getElementById("support").innerHTML = "HTML5 Canvas is not supported
in your browser."; }
Inthisexample,youtrytocreateacanvasobjectandaccessitscontext.Ifthereisanerror,youwill catchitandknowthatCanvasisnotsupported.Apreviouslydefinedsupportelementonthepageis updatedwithasuitablemessagetoreflectwhetherthereisbrowsersupportornot.
Thistestwillindicatewhetherthecanvaselementitselfissupportedbythebrowser.Itwillnot indicatewhichcapabilitiesoftheCanvasaresupported.Atthetimeofthiswriting,theAPIisstableand well-supported,sothisshouldgenerallynotbeanissuetoworryabout.
Additionally,itisagoodideatosupplyfallbackcontenttoyourcanvaselement,asshowninListing 2-3.
AddingaCanvastoaPage
AddingacanvaselementinanHTMLpageisprettystraight-forward.Listing2-4showsthecanvas elementthatcanbeaddedtoanHTMLpage.
Listing2-4.TheCanvasElement
<canvas height="200" width="200"></canvas>
Theresultingcanvaswillshowupasan“invisible”200×200pixelrectangleonyourpage.Ifyou wanttoaddaborderaroundit,youcouldusetheHTMLcodeshowninListing2-5tostylethecanvas withnormalCSSborders.
Listing2-5.CanvasElementwithaSolidBorder
<canvas id="diagonal" style="border: 1px solid;" width="200" height="200"> </canvas>
NotetheadditionoftheIDdiagonaltomakeiteasytolocatethiscanvaselementprogrammatically. AnIDattributeiscrucialtoanycanvasbecausealltheusefuloperationsonthiselementmustbedone throughscripting.WithoutanID,youwillhavedifficultylocatingtheelementtointeroperatewithit.
Figure2-2.AsimpleHTML5canvaselementonanHTMLpage
Notveryexciting,butasanyartistwouldtellyou,itisfullofpotential.Now,let’sdosomethingwith thispristinecanvas.Asmentionedbefore,itisnoteasytodrawadiagonallineonawebpagewithout HTML5Canvas.Let’sseehoweasyitisnowthatwecanuseCanvas.Listing2-6showshow,withjusta fewlinesofcode,youcandrawadiagonallineonthecanvasweaddedtothepageearlier.
Listing2-6.CreatingaDiagonalLineonaCanvas
<script>
function drawDiagonal() {
// Get the canvas element and its drawing context var canvas = document.getElementById('diagonal'); var context = canvas.getContext('2d');
// Create a path in absolute coordinates context.beginPath();
context.moveTo(70, 140); context.lineTo(140, 70);
// Stroke the line onto the canvas context.stroke();
}
window.addEventListener("load", drawDiagonal, true); </script>
Let’sexaminetheJavaScriptcodeusedtocreatethediagonalline.Itisasimpleexample,butit capturestheessentialflowofworkingwiththeCanvasAPI:
Youfirstgainaccesstothecanvasobjectbyreferencingaparticularcanvas’sIDvalue.Inthis example,theIDisdiagonal.Next,youcreateacontextvariableandyoucallthecanvasobject’s
getContextmethod,passinginthetypeofcanvasyouarelookingfor.Youpassinthestring“2d”togeta two-dimensionalcontext—theonlyavailablecontexttypeatthistime.
thestring"
webgl"astheargumentto
getContext.TheresultingcontexthasanentirelynewsetofdrawingAPIs:
capabilitiesthatarethoroughandcomplexenoughfortheirownbook.Althoughsomebrowsersareshipping
implementationsofWebGLtoday,notallvendorsareonboard.However,thepotentialofthree-dimensional
renderingontheWebiscompellingenoughthatweexpectrapiduptakeofsupportinthenextfewyears.Formore
information,consulttheWebGLsiteattheKhronosGroup(
http://www.khronos.org/webgl).Wewilltouchon
WebGLinalittlemoredetailinthefinalchapterofthisbook.
Youthenusethecontexttoperformdrawingoperations.Inthiscase,youcancreatethediagonal linebycallingthreemethods—beginPath,moveTo,andlineTo—passingintheline’sstartandend coordinates.
ThedrawingmethodsmoveToandlineTodonotactuallycreatetheline;youfinalizeacanvas operationanddrawthelinebycallingthecontext.stroke();method.Figure2-3showsthediagonal linecreatedwiththeexamplecode.
Figure2-3.Diagonallineonacanvas
Triumph!Althoughthissimplelinemaynotappeartobethestartofarevolution,keepinmindthat drawingadiagonallinebetweentwoarbitrarypointsusingclassicHTMLtechniqueswasaverydifficult maneuverinvolvingstretchedimages,strangeCSSandDOMobjects,orotherformsofblackmagic.Let usneverspeakofthemagain.
Asyoucanseefromthisexample’scode,alloperationsonthecanvasareperformedviathecontext object.Thiswillholdtruefortherestofyourinteractionwiththecanvasbecausealltheimportant functionswithvisualoutputareaccessibleonlyfromthecontext,notthecanvasobjectitself.This flexibilityallowsthecanvastosupportdifferenttypesofdrawingmodelsinthefuture,basedonthetype ofcontextthatisretrievedfromthecanvas.Althoughwewillfrequentlyreferinthischaptertoactions wewilltakeonthecanvas,keepinmindthatthisactuallymeansthatwewillbeworkingwiththe contextobjectthatthecanvassupplies.
ApplyingTransformationstoDrawings
Nowlet’slookatanotherwaytodrawonthecanvasusingtransformation.Inthefollowingexample,the resultisidenticaltothepreviousexample,butthecodeusedtodrawthediagonallineisdifferent.For thissimpleexample,youcouldarguethattheuseoftransformationaddsunnecessarycomplexity. However,youcanthinkofusingtransformationasabestpracticeformorecomplexcanvasoperations. You’llseethatwe’lluseitalotthroughouttheremainingexamples,anditiscriticaltounderstandingthe CanvasAPI’scomplexcapabilities.
Perhapstheeasiestwaytothinkofthetransformationsystem—atleast,theeasiestwaythatdoes notinvolveagreatamountofmathematicalformulaeandhand-waving—isasamodificationlayerthat sitsbetweenthecommandsyouissueandtheoutputonthecanvasdisplay.Thismodificationlayeris alwayspresent,evenifyouchoosenottointeractwithit.
Modifications,ortransformationsintheparlanceofdrawingsystems,canbeappliedsequentially, combined,andmodifiedatwill.Everydrawingoperationispassedthroughthemodificationlayertobe modifiedbeforeitappearsonthecanvas.Althoughthisaddsanextralayerofcomplexity,italsoadds tremendouspowertothedrawingsystem.Itgrantsaccesstothepowerfulmodificationsthatmodern image-editingtoolssupportinrealtime,yetinanAPIthatisonlyascomplexasitabsolutelyneedstobe.
Don’tbefooledintothinkingthatyouareoptimizingperformanceifyoudon’tusetransformation callsinyourcode.Thecanvasimplementationusesandappliestransformationsimplicitlyinits renderingengine,whetherornotyoucallthemdirectly.Itiswisertounderstandthesystemupfront becauseitwillbecrucialtoknowifyoustepoutsidethemostbasicdrawingoperations.
Akeyrecommendationforreusablecodeisthatyouusuallywanttodrawattheorigin(coordinate 0,0)andapplytransformations—scale,translate,rotate,andsoforth—tomodifyyourdrawingcodeinto itsfinalappearance,asshowninFigure2-4.
Figure2-4.Overviewoftransformationanddrawingattheorigin
Listing2-7.UsingTranslationtoCreateaDiagonalLineonaCanvas
<script>
function drawDiagonal() {
var canvas = document.getElementById('diagonal'); var context = canvas.getContext('2d');
// Save a copy of the current drawing state context.save();
// Move the drawing context to the right, and down context.translate(70, 140);
// Draw the same line as before, but using the origin as a start
6. Afterthelinehasbeensketched,youcanrenderittothecanvas(forexample, drawtheline)bycallingthecontext.strokemethod.
7. Finally,yourestorethecontexttoitscleanoriginalstate,sothatfuturecanvas operationsareperformedwithoutthetranslationthatwasappliedinthis operation.Figure2-5showsthediagonallinecreatedwiththeexamplecode.
Figure2-5.Translateddiagonallineonacanvas
Eventhoughyournewlinelooksremarkablyliketheoldone,youcreateditusingthepowerof transformations,somethingthatwillbecomemoreapparentasweprogressthroughtherestofthis chapter.
WorkingwithPaths
Althoughwecouldoffermanymoreexcitingexamplesfordrawinglines,wearereadynowtoprogressto somethingabitmorecomplex:paths.PathsintheHTML5CanvasAPIrepresentanyshapeyoucareto render.Ouroriginallineexamplewasapath,asyoumighthavegatheredfromtheconspicuous
beginPathcallusedtostartitoff.Butpathscanbeascomplicatedasyoudesire,withmultiplelineand curvesegmentsandevensubpaths.Ifyouarelookingtodrawalmostanyshapeonacanvas,thepath APIwillbeyourfocuspoint.
Whenembarkingonanyroutinetodrawashapeorpath,thefirstcallyoumakeisbeginPath.This simplefunctiontakesnoarguments,butitsignalstothecanvasthatyouwishtostartanewshape description.Thisfunctionismostlyusefultothecanvassothatitcancalculatetheinteriorandexterior oftheshapeyouarecreatingforlaterfillsandstrokes.
Apathalwaystrackstheconceptofacurrentlocation,whichdefaultstotheorigin.Thecanvas internallytracksthecurrentlocation,butyouwillmodifyitwithyourdrawingroutines.
Oncetheshapeisbegun,youcanuseavarietyoffunctionsonthecontexttoplotthelayoutofyour shape.You’vealreadyseenthesimplestcontextpathingfunctionsinaction:
• moveTo(x, y):movesthecurrentlocationtoanewdestinationof(x,y)without drawing.
• lineTo(x, y):movesthecurrentlocationtoanewdestinationof(x,y)drawinga straightlinefromthecurrentpositiontothenewone.
ThenextspecialpathingfunctionisacalltoclosePath.Thiscommandisverysimilarinbehaviorto thelineTofunction,withthedifferencebeingthatthedestinationisautomaticallyassumedtobethe originationofthepath.However,theclosePathalsoinformsthecanvasthatthecurrentshapehas closedorformedacompletelycontainedarea.Thiswillbeusefulforfuturefillsandstrokes.
Atthispoint,youarefreetocontinuewithmoresegmentsinyourpathtocreateadditional subpaths.OryoucanbeginPathatanytimetostartoverandclearthepathlistentirely.
Aswithmostcomplexsystems,itisoftenbettertoseetheminaction.Let’sdepartfromourline
function createCanopyPath(context) { // Draw the tree canopy
context.beginPath(); context.moveTo(-25, -50); context.lineTo(-10, -80); context.lineTo(-20, -80); context.lineTo(-5, -110); context.lineTo(-15, -110); // Top of the tree
context.lineTo(0, -140); context.lineTo(15, -110); context.lineTo(5, -110); context.lineTo(20, -80); context.lineTo(10, -80); context.lineTo(25, -50);
// Close the path back to its start point context.closePath();
}
function drawTrails() {
var canvas = document.getElementById('trails'); var context = canvas.getContext('2d');
context.save();
// Create the shape for our canopy path createCanopyPath(context);
// Stroke the current path context.stroke();
context.restore(); }
Allthecallsinthisroutineshouldbefamiliartoyoualready.Wefetchthecanvascontext,saveitfor futurereference,translateourpositiontoanewlocation,drawthecanopy,strokeitontothecanvas,and thenrestoreourstate.Figure2-6showstheresultsofourhandiwork,asimplylinerepresentationofa treecanopy.We’llexpandonthisaswegoforward,butit’sagoodfirststep.
Figure2-6.Asimplepathofatreecanopy
WorkingwithStrokeStyles
TheCanvasAPIwouldn’tbepowerfulorpopularifdeveloperswerestuckusingsimplestickdrawings andblacklines.Let’susethestrokestylingcapabilitiestomakeourcanopyalittlemoretree-like.Listing 2-10showssomebasiccommandsthatcanmodifythepropertiesofthecontextinordertomakethe strokedshapelookmoreappealing.
Listing2-10.UsingaStrokeStyle
// Increase the line width context.lineWidth = 4;
// Round the corners at path joints context.lineJoin = 'round';
Byaddingtheabovepropertiesbeforestroking,wechangetheappearanceofanyfuturestroked shapes—atleastuntilwerestorethecontextbacktoapreviousstate.
First,weincreasethewidthofthestrokedlinestofourpixels.
Next,wesetthelineJoinpropertytoround,whichcausesthejointsofourshape’ssegmentstotake onamoreroundedcornershape.WecouldalsosetthelineJointobevelormiter(andthe
correspondingcontext.miterLimitvaluetotweakit)tochooseothercorneroptions.
Finally,wechangethecolorofthestrokebyusingthestrokeStyleproperty.Inourexample,weare settingthecolortoaCSSvalue,butasyouwillseeinlatersections,itisalsopossibletosetthe
strokeStyletobeanimagepatternoragradientforfancierdisplays.
Althoughwearenotusingithere,wecouldalsosetthelineCappropertytobeeitherbutt,square,or
roundtospecifyhowlinesshoulddisplayattheendpoints.Alas,ourexamplehasnodanglinglineends. Figure2-7showsourspruced-uptreecanopy,nowstrokedwithawider,smoother,brownlineinsteadof theflatblacklinefrombefore.
Figure2-7.Stylishstrokedtreecanopy
WorkingwithFillStyles
Asyoumightexpect,strokingisnottheonlywaytoaffecttheappearanceofcanvasshapes.Thenext commonwaytomodifyashapeistospecifyhowitspathsandsubpathsarefilled.Listing2-11shows howsimpleitistofillourcanopywithapleasant,greencolor.
Listing2-11.UsingaFillStyle
// Set the fill color to green and fill the canopy context.fillStyle = '#339900';
context.fill();
Figure2-8.Filledtreecanopy
Becausewestrokedourcanopybeforefillingit,thefillcoverspartofthestrokedpath.Thisisdueto thefactthatthewidestroke—inourcase,fourpixelswide—iscenteredalongthelineofthepathshape. Thefillappliestoallpixelsontheinterioroftheshape,andassuchitwillcoverhalfofthestrokedline pixels.Shouldyoupreferthefullstroketoappear,youcansimplyfillbeforestrokingthepath.
FillingRectangularContent
Everytreedeservesastrongfoundation.Thankfully,weleftspaceforourtreetrunkintheoriginalshape path.Listing2-12showshowwecanaddthesimplestrenderingofatreetrunkbyusingthefillRect conveniencefunction.
Listing2-12.UsingthefillRectConvenienceFunction
// Change fill color to brown context.fillStyle = '#663300';
// Fill a rectangle for the tree trunk context.fillRect(-5, -50, 10, 50);
Here,weonceagainsetabrownfillstyle.Butinsteadofexplicitlydrawingthecornersofourtrunk rectangleusingthelineToability,wewilldrawtheentiretrunkinonestepbyusingfillRect.The
fillRectcalltakesthexandylocation,aswellasthewidthandheight,andthenimmediatelyfillsitwith thecurrentfillstyle.
Canvas Animations
Briansays
:“Theabilitytoclearrectanglesinthecanvasiscoretocreatinganimationsandgamesusing
theCanvasAPI.Byrepeatedlydrawingandclearingsectionsofthecanvas,itispossibletopresentthe
illusionofanimation,andmanyexamplesofthisalreadyexistontheWeb.However,tocreateanimations
thatperformsmoothly,youwillneedtoutilizeclippingfeaturesandperhapsevenasecondarybuffered
canvastominimizetheflickeringcausedbyfrequentcanvasclears.Althoughanimationsarenotthefocus
ofthisbook,checkoutthe‘PracticalExtra’sectionsofthischapterforsometipsonusingHTML5to
animateyourpages.”
Figure2-9showsoursimple,flatlyfilledtreetrunkattachedtoourpreviouscanopypath.
Figure2-9.Treewithfilledrectangulartrunk
DrawingCurves
Theworld,particularlythenaturalworld,isnotfilledwithstraightlinesandrectangles.Fortunately,the canvasprovidesavarietyoffunctionsforcreatingcurvesinourpaths.Wewilldemonstratethesimplest option—aquadraticcurve—toformapaththroughourvirtualforest.Listing2-13demonstratesthe additionoftwoquadraticcurves.
Listing2-13.DrawingaCurve
// Save the canvas state and draw the path context.save();
context.translate(-10, 350); context.beginPath();
context.moveTo(0, 0);
context.quadraticCurveTo(170, -50, 260, -190); // The second curve continues down and right context.quadraticCurveTo(310, -250, 410,-250); // Draw the path in a wide brown stroke context.strokeStyle = '#663300'; context.lineWidth = 20;
context.stroke();
// Restore the previous canvas state context.restore();
Asbefore,oneofthefirstthingswewilldoissaveourcanvascontextstate,becausewewillbe modifyingthetranslationandstrokeoptionshere.Forourforestpath,wewillstartbymovingbackto theoriginanddrawingafirstquadraticcurveupandtotheright.
AsshowninFigure2-10,thequadraticCurveTofunctionbeginsatthecurrentdrawinglocationand takestwox,ypointlocationsasitsparameters.Thesecondoneisthefinalstopinourcurve.Thefirst onerepresentsacontrolpoint.Thecontrolpointsitstothesideofthecurve(notonit)andactsalmost asagravitationalpullforthepointsalongthecurvepath.Byadjustingthelocationofthecontrolpoint, youcanadjustthecurvatureofthepathyouaredrawing.Wedrawasecondquadraticcurveupandto therighttocompleteourpath;thenstrokeitjustaswedidforourtreecanopybefore(onlywider).
Figure2-10.Quadraticcurvestart,end,andcontrolpoints