Html5 an-introduction-ebook-no-ads-2011-developer


Published on

* Trang tài nguyên IBM developerWorks Việt Nam:
* Trang Fanpage của IBM developerWorks Việt Nam:

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Html5 an-introduction-ebook-no-ads-2011-developer

  1. 1. an Developer eBook®HTML5:AnIntroduction
  2. 2. 2 Learning About HTML54 Differences Between HTML 4 and HTML56 Multimedia In HTML58 The HTML5 Video Element10 How To Use the Audio Tag12 Using The HTML5 Canvas Element4826Contents…HTML5 is an emerging standard web developers are embracing everywhere. TheHTML5 standards define new functionality that is being embraced by most ofthe key web browsers, including Microsoft Internet Explorer 9. In this ebook, youwill be introduced to the basic features of HTML5 that you can use within yourweb sites now.This content was adapted from QuinStreet’s HTMLGoodieswebsite. Contributors:.David Fiedler and Scott Clark.HTML5: An Introduction1210
  3. 3. 2 HTML5: An Introduction an Developer eBook. © 2011,, a division of QuinStreet, Inc.Back to ContentsHTML5: An IntroductionTML5, depending on who you listen to, maybe either a disruptive new technology thathas the potential to bring entire companiesto their knees, or a smooth transition fromcurrent HTML 4.0 that promises to make life much easierfor developers. Both are at least partially true, and in thiscontinuing series, I hope to help you make sense out ofHTML5: both business sense and nuts-and-bolts coding-level sense.HTML5 is most definitely a work in progress. It began totake shape back in 2004, and the official specificationmay not be actually complete until the year 2022! ButHTML5 is already here, in everything from your currentdesktop browser to your new smartphone, so there’s noproblem with getting started.So Let’s Get Started with HTML5Perhaps the most important thing to understand aboutHTML5 is not the coding details and changes themselves,but the high-level functions they give you access to. Infact, HTML5 is all about high-level functions rather thandetails. For instance, instead of thinking of multimediaobjects and then defining them as video or audio and soon, in HTML5 you can simply write something like:<video src=”watchthis.mp4” width=”640”height=”480”> <a href=”watchthis.mp4”>Here’s my video</a></video>This functional methodology extends even to typicalpage coding. We’re all used to writing complex pagesin terms of low-level objects like </div>, which is kindof amorphous and easy to lose track of. So we oftenattempt to keep track of things by coding like this:Web Developer Basics: Learning About HTML5By David Fiedler and Scott ClarkH<div id=”header”><H1>Web Developer Basics: Learning AboutHTML5</H1><p class=”credit”>by David Fiedler</p></div>In HTML5, we can cut right to the chase. We’re writing aheader, and now we can code it that way:<header><H1>Web Developer Basics: Learning AboutHTML5</H1><p class=”credit”>by David Fiedler</p></header>So what, you might say at this point. Well, it’s not just theheader of a page that we can now view as a completefunctional object, it’s almost everything we use on a dailybasis: <header>, <footer>, <article>, <section>, <nav>,<menu>, <figure>. This gives us tremendous flexibility
  4. 4. 3 HTML5: An Introduction an Developer eBook. © 2011,, a division of QuinStreet, Inc.Back to ContentsHTML5: An Introductiondemonstrates some real power. Paste this simple littledocument into a text file, and call it something like foo.html:<!DOCTYPE html><html lang=”en”><head><meta charset=”utf-8”><title>You Can Edit This</title></head><body><h1>I Mean, You Can Really Edit This</h1><p contenteditable=true>Now is the time for all good cats to cometo the aid of their catnip.</p></body></html>The only new thing here that will jump out at you is theattribute of contenteditable on the paragraph tag. Youcan use this on any element, not just a paragraph, andit takes effect for everything within that element. Now,open this file using any modern browser and you’ll seethat you can indeed edit the paragraph - but not theheading! - Right in the browser.But wait, there’s more! Change that paragraph as muchas you like, then save the page to your computer as anew HTML file. Open it up in a text editor...and presto,the source code has changed to reflect the text changesyou made in the browser. Shazam!in terms of how we can think of the page. So it’s not justeasier to understand the structure of the page, it’s easierto correctly code the structure of the page.Begin At the BeginningThe beginning of many modern HTML 4.0 pages lookssomething like this:<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0Strict//EN” “”>But in our brave new world of HTML5, all we need is:<!DOCTYPE html>Similarly, the complex XHTML boilerplate declarationsmany people use can be simply replaced by:<html lang=”en”>and encoding declarations such as<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8”>can be toned down to a mere<meta charset=”utf-8”>Oh, and we may as well get this next bit out of the waynow, even though I hesitate to mention it for fear of beingresponsible for people writing near-incomprehensibleHTML5 pages. You no longer need those double quotesaround attributes, so that <p class=credit> is now aslegal as <p class=”credit”>. But please use this powerwisely.A Bit of MagicJust to show that HTML5 isn’t only about structure andsaving keystrokes here and there, here’s a nice exampleof an attribute feature that is simple on the surface, but
  5. 5. 4 HTML5: An Introduction an Developer eBook. © 2011,, a division of QuinStreet, Inc.Back to ContentsHTML5: An Introductionow it’s time to take a few steps back and takea look at some of the differences betweenHTML 4 and HTML5.This is intended to be a useful overview, not anexhaustive reference, but remember that things arestill and always changing. Thecomplete, up to date list ofall the technical differencesmay always be found on theW3C’s site. You also may wantto refer to this document forthe actual details of the HTML5specification itself.The first thing you should knowis that, perhaps for the first time,the development of a languagestandard is acknowledging thereal world. In order to keep filecompatibility with the currentstandard - which is technicallyHTML 4.01 - the brave decisionwas made to separate theway the web browser renders files from the way we, asdevelopers, must write them. So the browser, or “useragent”, must still process HTML4 constructs like the centerelement, because there will still be millions of files on theInternet that happen to use it. But we won’t be writing anymore HTML with center; it’s simply being dropped fromthe language (use CSS instead). This compatibility goesboth ways: older browsers can (and will) simply ignoreHTML5 code without screwing things up.No More FramesThis is great news to those of us who slogged through the1990s. To be exact, the elements frame, frameset, andnoframes are being removed from the language, as wellas acronym, applet, basefont, big, blink, center , dir, font,isindex, strike , tt and u. All of these can be handled usingCSS or other methods.You’ll also have to learn to get along without usingtables for layout; while tablesthemselves are still part ofHTML5, they’re not intended forplacing pixels any more. Here’swhat the spec says:“Tables must not be used aslayout aids. Historically, someWeb authors have misused tablesin HTML as a way to controltheir page layout. This usage isnon-conforming, because toolsattempting to extract tabulardata from such documents wouldobtain very confusing results.”So all the attributes that letpeople create those perfectlylaid-out, tinted tables are gone, like align, bgcolor,border, cellpadding, cellspacing, height, nowrap, rules,valign, and the big one: width. The mantra: use CSSinstead.I’ve been trying my best to break it to you slowly, butfrankly, all presentational elements are coming out ofHTML5. My advice: learn lots more CSS, until you canquote chapter and verse in your sleep.Good NewsThe good news is that even though this is a big change,it’s a change for the better. Browsers of the future (justWeb Developer Basics:Differences between HTML 4 and HTML5By David Fiedler and Scott ClarkN
  6. 6. 5 HTML5: An Introduction an Developer eBook. © 2011,, a division of QuinStreet, Inc.Back to ContentsHTML5: An Introductionanother month or two!) will become more powerfulbecause of the move towards the cloud, so that they’llbe able to handle more on their own. We’ve alreadyseen that with things like Ajax, and now with video/audioembedding and such, it will be far easier for us to codein a straightforward manner and let the browser figureout the details. For instance, new structure elementsinclude article, aside, figcaption, figure, footer, header,hgroup, nav, section, and summary, all of which refer tothe structure of the document itself and leave renderingto the browser.There are still some new elements that deal with texton a detailed level, however: you’ll code wbr when youthink it’s possible to do a line break, but the browser willdecide for you. Another hint element is bdi, used to markan area where bidirectional text formatting can be done(primarily for mixing left-right and right-left languagesin a single document). Its complement, bdo, lets youexplicitly override and force a particular directionality.For even more slick internationalization, the elementsruby, rp, and rt are included for ruby annotations, whichare meant for pronunciation aids rather than for Ruby OnRails programmers.The more high-level new elements include things likecanvas, meant for specifying an area for drawing abitmapped graphic on the fly, such as a data graph orgame graphic; meter is a placeholder for a numericmeasurement of an expected size (and is eerily similarto format in ancient FORTRAN), while progress is itsgraphical counterpart, to be used where you want aprogress bar. Last, but not least, there are the multimediaelements (audio, video, source, embed) that we cover inanother segment of this ebook.
  7. 7. 6 HTML5: An Introduction an Developer eBook. © 2011,, a division of QuinStreet, Inc.Back to ContentsHTML5: An IntroductionThat’s all the code you need to display MPEG-4/H.264video in an HTML5 browser that supports the MPEG-4/H.264 video format, with a few extra goodies eventhrown in such as a predefined video size, defaultvideo controls, and a still thumbnail. Unfortunately, atthis writing, only Apple’s Safari and Google’s Chromebrowsers will work natively withthis particular format.Free MeMPEG-4 format has one otherproblem which is not technical;it’s not a “free” format. It’scovered by patents and thereare licensing fees involved,at least for broadcasters andbrowser manufacturers. That’swhy Mozilla Firefox, Opera, anda few other browsers supportOgg Theora. Google recentlyannounced it was freeing theVP8 video format it had acquiredwith On2 Technologies, andsimultaneously announced broad industry support forthe WebM container format using VP8 video and Vorbisaudio.As many developers will remember from the 1990s, thereality of competing standards is that browsers end upimplementing them differently, so you have to keep thedifferences in mind. Luckily, “all it takes” at this pointin time for universal support (except for some mobileplatforms) is to have all three different formats availablefor each of your videos to satisfy all the HTML5 browsersand some extra a fallback scheme for non-HTML5 browsers (which basically means the all-purposeWeb Developer Basics: Multimedia in HTML5By David Fiedler and Scott Clarkow you’ll see how support for variousmultimedia formats in HTML5 will makethings much easier for you as a developer...eventually.See Me, Hear MeWe’ll start with the good news.HTML5 is fairly intelligent aboutpicking the right default forpresenting the most optimumaudio or video. Couple thatwith the absolute minimumcoding that’s needed to handlemultimedia in HTML5 and youhave a pretty good situation fordevelopers.The bad news is that becausethe people diligently working onthe HTML5 specification triedto compromise between openformats and de facto standardformats and so on, support fornative codecs in HTML5 is slightly lacking: there isn’tany. It’s up to the browser to support formats, and upto the developer to supply them. What’s emerged fromthat are a few relatively new standards. So unless you’rea video or audio enthusiast, you may have to learn a fewnew things (and worse, convert your legacy media!). Butwhen all is said and done, programs do all the hard workanyway, so it’s certainly not a deal-breaker.<video controls width=”640” height=”480”src=”sample.mp4” poster=”sample.jpg”></video>N
  8. 8. 7 HTML5: An Introduction an Developer eBook. © 2011,, a division of QuinStreet, Inc.Back to ContentsHTML5: An IntroductionFlash plugin). Love it or hate it, you can’t live without ityet.<video controls width=”640” height=”480”poster=”sample.jpg”> <source src=”sample.mp4” type=’video/mp4;codecs=”avc1.42E01E, mp4a.40.2”’> <source src=”sample.webm” type=’video/webm;codecs=”vp8, vorbis”’> <source src=”sample.ogv”  type=’video/ogg;codecs=”theora, vorbis”’> <object width=”640” height=”480”type=”application/x-shockwave-flash”data=”flowplayer-3.2.1.swf”> <param name=”movie” value=”flowplayer-3.2.1.swf”> <param name=”allowfullscreen” value=”true”> <param name=”flashvars”value=’config={“clip”: {“url”: “”, “autoPlay”:false,“autoBuffering”:true}}’> <p>If you can read this, you’re using a pre-HTML5 browser without Flash.</p> </object></video>This extra MIME type specification certainly isn’t thereto pretty up the code, and it’s not strictly necessary,but if you don’t write it in accurately, then the browseris going to have to download each video file format inorder until it finds one that it can play. And by that, wemean downloading the entire video in the worstcase, that would be a full three times! So it takes a fewextra seconds to paste in those types and codecs, butnow you know why you should do it.Now that you’ve seen some of the video markup, theaudio will seem simple by comparison. Once more, it’squite possible to let the HTML5 browser do a lot of thework:<audio controls src=”sample.ogg”></audio>And again, in the real world, it’s recommended toprovide a number of format options for the browser:<audio controls preload=”metadata”> <source src=”sample.mp3”> <source src=”sample.ogg”> <!-- Flash fallback code or text would gohere --></audio>Both the <video> and <audio> can take anotherimportant parameter, shown above, called preload(which was formerly implemented as autobuffer withslightly different syntax). The values for preload canbe auto (download the media file to the browser inadvance), none (do not preload the media), or metadata(just download enough metadata to discover theduration and other information of the media file). Sowith a little extra care in coding, you can make the user’sexperience much better.
  9. 9. 8 HTML5: An Introduction an Developer eBook. © 2011,, a division of QuinStreet, Inc.Back to ContentsHTML5: An IntroductionWeb Developer Basics:The HTML5 Video ElementBy David Fiedler and Scott ClarkTML5’s video element is conceptually easy towork with, since at bottom it’s been designedlike the <img> tag...just code and go:<video src=”sample.mp4” width=”640”height=”480”></video>Unfortunately, in the real world, things aren’t quite soeasy. Due to licensing and other restrictions, you can’tsimply assume that the user’s software will properlydisplay your video in MPEG-4/H.264 format, so at thispoint you’ll have to supply the same video in openformats as well as providing a Flash-based fallback forpre-HTML5 browsers--something like this:<video controls width=”640” height=”480”poster=”sample.jpg”><source src=”sample.mp4”  type=”video/mp4”><source src=”sample.ogv”  type=”video/ogg”><source src=”sample.webm” type=”video/webm”>   <object width=”640” height=”480”type=”application/x-shockwave-flash”data=”player.swf”>       <param name=”movie” value=”player.swf”>       <param name=”flashvars” value=”controlbar=over&amp;image=sample.jpg&amp;file=sample.mp4”>       <img src=”sample.jpg” width=”640”height=”360” alt=”Sample”title=”No direct video playbackcapabilities, so please download the videobelow”>   </object></video><p>     <strong>Download Video:</strong>       Closed Format: <a href=”sample.mp4”>”MP4”</a>       Open Format:   <a href=”sample.ogv”>”Ogg”</a>       WebM Format:   <a href=”sample.webm”>”WebM”</a></p>Since this isn’t the kind of thing most developers liketo memorize, it’s good that someone has written up ahandy free code generator that lets you specify all yourparameters and video sizes and so on. But there’s morenitty-gritty to deal with, specifically transcoding thoseextra formats.Preaching To the ConvertedUnless you have lots of video files and an actualsoftware budget, your best bet is free conversionsoftware. Currently, the best selection for that isHandbrake, which is fully open source, runs onWindows, Mac OS X, and Linux, and will convert mostmultimedia file formats to MP4 or Ogg Theora (whenH
  10. 10. 9 HTML5: An Introduction an Developer eBook. © 2011,, a division of QuinStreet, Inc.Back to ContentsHTML5: An Introductionwe get to audio, you’ll find that it works just as wellfor those formats, too). If you’d rather be modern,OS-independent, and stay in the cloud, sites such asMediaConverter and Zamzar can accommodate youwith free online transcoding services (the latter siteeven supports the relatively new WebM format).The full list of attributes for the HTML5 video element atthis time includes the following, with usage notes:• src - The URL of the video. This overridesthe source element, if present.• poster - The URL of a still picture toshow while the video is not playing.• preload - This can have the value none,metadata, or auto. Auto will download theentire file if possible; metadata will downloadjust the parameters so that the length, size, andtype of the video can be identified, and nonewill do nothing, which saves bandwidth.• autoplay - This boolean, if present,triggers the video to play as soon as it isfully buffered or ready to stream.• loop - Also a boolean; if loop is present, the video willrepeat endlessly in the absence of user intervention.• audio - This attribute, which controls the audioportion of the video, is still in development.Currently, it can take only a single value: muted,which means that the audio volume will initially beset to zero. The intent is to allow an autoplayingvideo to start and get the user’s attention, butwithout blaring audio that would cause theuser to close the entire tab in disgust :-)• controls - A boolean attribute that specifiesthe browser should provide a set of defaultvideo controls. If it doesn’t appear, you’ll haveto design and code your own controls.• width, height - these size attributes control thesize of the area reserved for the video on thepage, but not necessarily its exact dimensions.While it takes a bit more work, generally in the Javascriptdepartment, to create your own controls and errorhandling, all it takes is some CSS to modify the look ofthe video element:<!DOCTYPE html>  <html lang=”en”>  <head>      <meta charset=”utf-8”>      <title>File in same directory</title><style type=”text/css”>video {         width: 800px;         height: 600px;         position: relative;     }</style></head><body><P><video source src=”airplane.webm” controlsautoplay>    Your browser does not support the videotag.</video><P></body>  </html>
  11. 11. 10 HTML5: An Introduction an Developer eBook. © 2011,, a division of QuinStreet, Inc.Back to ContentsHTML5: An IntroductionYou use the <audio> tag just like you use any otherelement:<audio autoplay=”autoplay” controls=”controls”>    <source src=”music.ogg” />    <source src=”music.mp3” />  </audio>You can also include the sourcefile’s location in the beginning<audio> tag, rather thanbetween the two, like this:<audio src=”music.ogg”controls=”controls”>Also note that you can point thesrc to a file located on the serverwith your web page (a relativeURL, like /audio/music.ogg), ora file located elsewhere on theweb (an absolute URL, such as will likely want to include some text inside the tag sothat users whose browsers do not support the <audio>tag will have a clue as to what is going on (and why theyaren’t seeing the audio control on the page). You do thatlike this:<audio src=”horse.ogg” controls=”controls”>Your browser does not support the audioelement.</audio>You can use any HTML elements that are supportedHTML5 Primer: How To Use the Audio TagBy David Fiedler and Scott Clarkow we’re going to expand upon ourdiscussion on multimedia and delve furtherinto HTML5’s <audio> tag.The <audio> tag is new to HTML, like the <video> tag,and allows developers to embed music on their websites(and unlike earlier attempts to add audio to a website,it isn’t limited to old-fashionedmidi music). That said, it doeshave limitations on the types offiles that can be used. Currentlyany recent browser that is basedon Webkit, such as Chrome andSafari, supports the use of regular.mp3 files. Others, such as Firefox,only support the .ogg format.The good news is that youcan either convert your filesfrom .mp3 to .ogg (one audioconversion tool,, can beused online) or just supply twoversions of your audio file, onein each format. When Safari, forinstance, comes across the <audio> tag, it will ignore the.mp3 file and move directly to the .ogg file.So How Is the <audio> Tag Used on the Page?When the audio tag is used, it will look something likeFigure 1 (obviously you will only see it if your browsersupports it):Figure 1: The Audio Tag in UseN
  12. 12. 11 HTML5: An Introduction an Developer eBook. © 2011,, a division of QuinStreet, Inc.Back to ContentsHTML5: An Introductionwithin the <audio> tag, such as italics, bold, links, objectssuch as Flash, etc.The <audio> Tag’s AttributesThe <audio> tag supports the full range of standardattributes in HTML5. These attributes are supported byall HTML5 tags, with very few exceptions. They include:• accesskey - this specifies a keyboard shortcut for agiven element• class - this specifies a classname for a given element,to be used in conjunction with a style sheet• contenteditable - specifies whether a user is allowedto edit the content• contextmenu - specifies the context menu for a givenelement• dir - specifies the direction of the text for content in agiven element• draggable - specifies if a user is allowed to drag agiven element• dropzone - specifies the event that occurs when anitem or data is dragged and dropped into a givenelement• hidden - specifies if a given element is hidden or not• id - specifies a unique identificationfor a given element• lang - specifies a language code forthe content in a given element• spellcheck - specifies if a specific element will needto be subjected to a spelling and grammar check• style - defines an inline style for a specific elementtabindex - specifies the tab order of a specificelement• title - specifies a title for a specific elementNew attributes for the <audio> tag include the following:• autoplay - if this attribute is included, the audio willbegin to play once it is ready• controls - if this one is included, controls for the audiofile will be included on the page (which is a greatidea--it is very annoying to not have a way to stop theaudio from playing)• loop - if this one is included, the audio will loop andplay again once it has finished• preload - this one has three parameters: auto, whichplays once it has loaded, metadata, which onlydisplays the data associated with the audio file, andnone, which means it will not preload• src - this one’s value is simply the URL of the audio fileyou wish to playYou can see some of the new attributes in action here:<audio loop=”loop” autoplay=”autoplay”controls=”controls”>    <source src=”music.ogg” />    <source src=”music.mp3” />  </audio>The <audio> tag has a lot of attributes which can be usedfor additional controls, including the event attributesin HTML5. Events include window events, which aretriggered for the window object, form events, which aretriggered by actions that occur within an HTML form,keyboard and mouse events, and media events. Many ofthe events are the same as those included with previousversions of HTML.
  13. 13. 12 HTML5: An Introduction an Developer eBook. © 2011,, a division of QuinStreet, Inc.Back to ContentsHTML5: An Introductiondoesn’t yet support the canvas element. Actually, it’smore than “should”’s “must” in the words of the W3Cdefinition:“When authors use the canvas element, they mustalso provide content that, when presented to the user,conveys essentially the same function or purpose as thebitmap canvas. This contentmay be placed as content of thecanvas element.”So in a real-world web page,you’d want to include somethingthat displays the closestequivalent to the contents ofyour fancy bitmapped graphiccanvas. If your canvas showed astock graph, you could use thecurrent stock price. The intentis to allow the widest possibleaudience to see the mostvaluable and useful content, afterall. The good news is that thecurrent versions of all leadingmodern browsers already support canvas...except, ofcourse, Internet Explorer (though it’s coming in IE9).Also, note that you must name each specific canvaselement with its own id so you can address it later in yourJavaScript. And while most basic tutorials show all kindsof boxes and graphic elements laboriously renderedpoint by point, in reality most canvas applications willinvolve user interactivity, image transformations, oralgorithm-based graphic rendering, such as Apple’s clockwidget. Or all three, such as this mind-boggling CanvasAquarium ( Developer Basics:Using The HTML5 Canvas ElementBy David Fiedler and Scott Clarkanvas is a unique concept. Unlike the rest ofthe HTML world that consists of well-definedpieces that designers and developers loveto place in exactly the right spot, the Canvaselement provides a virtual Etch-a-Sketch-like area wherealmost anything can be made to happen. It’s relativelyeasy to describe but, like most open-ended concepts,more difficult to characterize.Canvas is a bit-mapped areawhose width and heightdimensions are specified asattributes (defaulting to 300 and150 respectively); the purposecan be virtually anything, and theintention is that a canvas elementwill be rendered by scripting.Show Me the HTML5Code!Clearly the simplest possibilityis <canvas></canvas>, and thatgets you your very own 300x150area, but you won’t see itbecause the default is transparent (speaking of defaults,anything you actually draw on a canvas is black unlessyou specify otherwise). A more realistic beginning issomething like this:<canvas id=”drawme” width=”400” height=”200”>   If you can read this, your browser does notsupport Canvas.<canvas>Note that, similar to the video element, you can (andshould) provide fallback content in case the browserC
  14. 14. 13 HTML5: An Introduction an Developer eBook. © 2011,, a division of QuinStreet, Inc.Back to ContentsHTML5: An IntroductionThe Mozilla Developer Network TemplateMozilla’s Developer Network ( has created a nice template for use indemonstrating basic canvas functions, so we’ll use that asthe basis of our own example code:<!DOCTYPE html><html lang=”en”> <head>   <meta charset=”utf-8”>   <title>Canvas Tutorial Template</title>   <script type=”text/javascript”>     function draw(){       var canvas = document.getElementById(‘tutorial’);       if (canvas.getContext){           var ctx = canvas.getContext(‘2d’);////    drawing code goes below here//           ctx.fillStyle = “rgb(255,0,0)”;           ctx.fillRect(0, 0, 150, 150);////    drawing code goes above here//       }     }   </script>   <style type=”text/css”>     canvas { border: 1px solid black; }   </style> </head> <body onload=”draw();”>   <canvas id=”tutorial” width=”150”height=”150”>       Fallback content goes here.   </canvas> </body></html>The most important piece of all this is actually where youcall getElementById using your named canvas id (whichlocates your canvas in the DOM), then call getContextto initialize the actual drawing context. Once you have acontext (which we point to using ctx), you can manipulateit using anything you like in the 2D drawing APIs.And the Function Is....In this case, we’ve used fillStyle to select solid red andfillRect to describe the boundaries of the rectangle tobe drawn. You can now use this template to quicklyexperiment with any or all of the other functions in theAPIs, by simply writing more complex code in place ofthose two lines. The x,y origin is defined to be at thetop left, so knowing that, you can start making use offunctions such as:• fillRect (x,y, width, height) - paints the describedrectangle (filled using the current fillStyle)• strokeRect (x,y, width, height) - paints the describedrectangle outline (using the current strokeStyle)• clearRect (x,y,width,height) - clears the describedrectangle and makes it transparent (transparent black,to be technical)For true drawing, you need the ability to draw linesand curves, and place your virtual pen anywhere on thecanvas, so these functions are key:• beginPath() - starts a new drawing• moveTo(x,y) - places the pen at the x,y location• lineTo(x,y) - draws a line from the penlocation to the x,y location• arc(x, y, radius, startAngle, endAngle,anticlockwise) - draws an arc at x,y using radiusfrom startAngle to endAngle (in radians). Thearc is drawn clockwise unless the optionalboolean anticlockwise parameter appears.• stroke() - renders the drawing in outline form• fill() - renders the drawing in filled form