<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Think Vitamin &#187; Jamie Newman</title>
	<atom:link href="http://thinkvitamin.com/author/jamie-newman/feed/" rel="self" type="application/rss+xml" />
	<link>http://thinkvitamin.com</link>
	<description>The Web Practitioner&#039;s Blog</description>
	<lastBuildDate>Thu, 09 Feb 2012 16:41:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>How to Draw with HTML 5 Canvas</title>
		<link>http://thinkvitamin.com/code/how-to-draw-with-html-5-canvas/</link>
		<comments>http://thinkvitamin.com/code/how-to-draw-with-html-5-canvas/#comments</comments>
		<pubDate>Wed, 09 Sep 2009 07:01:05 +0000</pubDate>
		<dc:creator>Jamie Newman</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Articles]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=3054</guid>
		<description><![CDATA[Among the set of goodies in the HTML 5 specification is Canvas which is a way to programmatically draw using JavaScript. We&#8217;ll explore the ins and outs of Canvas in this article, demonstrating what is possible with examples and links. Why Do You Need Canvas? Canvas can be used to represent something visually in your [...]]]></description>
			<content:encoded><![CDATA[<p>Among the set of goodies in the HTML 5 specification is Canvas which is a way to programmatically draw using JavaScript.</p>
<p>We&#8217;ll explore the ins and outs of Canvas in this article, demonstrating what is possible with examples and links.</p>
<p><span id="more-3054"></span></p>
<p><a href="http://membership.thinkvitamin.com/gifts/plans?cid=129"><img src="http://img.skitch.com/20101227-xfk651ecm49yeb15rucp9a6ixh.png" alt="Give a Think Vitamin Membership gift subscription to someone" /></a></p>
<h3>Why Do You Need Canvas?</h3>
<p>Canvas can be used to represent something visually in your browser. For example:</p>
<ul>
<li>Simple diagrams</li>
<li>Fancy user interfaces</li>
<li>Animations</li>
<li>Charts and graphs</li>
<li>Embedded drawing applications</li>
<li>Working around CSS limitations</li>
</ul>
<p>In basic terms it&#8217;s a very simple pixel-based drawing API, but used in the right way it can be the building block for some clever stuff.</p>
<h3>What Tools Are at Your disposal?</h3>
<p><strong>Drawing tools</strong></p>
<ul>
<li>Rectangles</li>
<li>Arcs</li>
<li>Paths and line drawing</li>
<li>Bezier and quadratic curves</li>
</ul>
<p><strong>Effects</strong></p>
<ul>
<li>Fills and strokes</li>
<li>Shadows</li>
<li>Linear and radial gradients</li>
<li>Alpha transparency</li>
<li>Compositing</li>
</ul>
<p><strong>Transformations</strong></p>
<ul>
<li>Scaling</li>
<li>Rotation</li>
<li>Translation</li>
<li>Transformation matrix</li>
</ul>
<p><strong>Getting data in and out</strong></p>
<ul>
<li>Loading external images by URL, other canvases or data URI</li>
<li>Retrieving a PNG representation of the current canvas as a data URI</li>
</ul>
<p>The excellent <a href="http://blog.nihilogic.dk/2009/02/html5-canvas-cheat-sheet.html">Canvas cheat sheet</a> is a great reference of the commands available.</p>
<h3>Getting Started</h3>
<p>To use Canvas, you&#8217;ll need two things</p>
<ul>
<li>A Canvas tag in the HTML to place the drawing canvas</li>
<li>JavaScript to do the drawing</li>
</ul>
<p>The Canvas tag is basically an img tag without any data. You specify a width and a height for the drawing area. Instead of an alt attribute, you can enclose HTML within the canvas tag itself for alternative content.</p>
<p>Example of a Canvas tag:</p>
<p><code>&lt;canvas id="myDrawing" width="200" height="200"&gt;<br />
&lt;p&gt;Your browser doesn't support canvas.&lt;/p&gt;<br />
&lt;/canvas&gt;</code></p>
<p>With a Canvas element in the HTML, we&#8217;ll add the JavaScript. We need to reference the Canvas element, check the browser is Canvas-compatible and create a drawing context:</p>
<p><code>var drawingCanvas = document.getElementById('myDrawing');<br />
// Check the element is in the DOM and the browser supports canvas<br />
if(drawingCanvas.getContext) {<br />
    // Initaliase a 2-dimensional drawing context<br />
    var context = drawingCanvas.getContext('2d');<br />
    //Canvas commands go here<br />
}</code></p>
<p>Checking for the getContext() method on a canvas DOM object is the standard way of determining canvas compatibility.</p>
<p>The context variable now references a Canvas context and can be drawn on.</p>
<h3>Basic Drawing</h3>
<p>So, let&#8217;s get started with an example to demonstrate the basics. We&#8217;re going to draw a smiley face, similar to the one on the <a href="http://acid2.acidtests.org/reference.html">Acid2 reference rendering</a>.</p>
<p>If we think about the face as a set of basic shapes, we have:</p>
<ol>
<li>A circle, with a black stroke and yellow fill for the face.</li>
<li>2 circles with a black stroke and white fill and with an inner circle of filled green for the eyes.</li>
<li>A curve for the smile.</li>
<li>A diamond for the nose.</li>
</ol>
<p>Let&#8217;s start by creating the round face:</p>
<p><code>// Create the yellow face<br />
context.strokeStyle = "#000000";<br />
context.fillStyle = "#FFFF00";<br />
context.beginPath();<br />
context.arc(100,100,50,0,Math.PI*2,true);<br />
context.closePath();<br />
context.stroke();<br />
context.fill();</code></p>
<p>You can see from the above that we start by defining some colours for the stroke and fill, then we create a circle (an arc with a radius of 50 and rotated through the angles of 0 to 2*Pi radians). Finally, we apply the stroke and fill that has been defined previously.</p>
<p>This process of setting styles, drawing to co-ordinates and dimensions and finally applying a fill or stroke is at the heart of Canvas drawing. When we add the other face elements in, we get:</p>
<p><a href="http://carsonified.com/wp-content/uploads/2009/08/smileyface.png"><img class="alignnone size-full wp-image-3056" title="smileyface" src="http://carsonified.com/wp-content/uploads/2009/08/smileyface.png" alt="smileyface" width="470" height="162" /></a></p>
<p><a href="http://www.ryancarson.com/uploads/canvas/smiley.html">Download the full source code of the smiley face example</a></p>
<h3>Effects and Transformations</h3>
<p>Let&#8217;s see how we can manipulate an existing image in canvas. We can load external images using the drawImage() method:</p>
<p><code>context.drawImage(imgObj, XPos, YPos, Width, Height);</code></p>
<p>Here&#8217;s the image we&#8217;re going to play with:</p>
<p><a href="http://carsonified.com/wp-content/uploads/2009/08/cocktail.png"><img class="alignnone size-full wp-image-3057" title="cocktail" src="http://carsonified.com/wp-content/uploads/2009/08/cocktail.png" alt="cocktail" width="470" height="111" /></a></p>
<p>We&#8217;re going to give the image a red frame. For this we&#8217;ll use a rectangle and fill it with a radial gradient to give it a bit of texture.</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">&lt;code&gt;//Create a radial gradient.
var gradient = context.createRadialGradient<span class="br0">&#40;</span><span style="">90</span>,<span style="">63</span>,<span style="">30</span>,<span style="">90</span>,<span style="">63</span>,<span style="">90</span><span class="br0">&#41;</span>;
gradient.addColorStop<span class="br0">&#40;</span><span style="">0</span>, '#FF0000'<span class="br0">&#41;</span>;
gradient.addColorStop<span class="br0">&#40;</span><span style="">1</span>, '#<span style="">660000</span>'<span class="br0">&#41;</span>; 
//Create radial gradient box for picture frame;
context.fillStyle = gradient;
context.fillRect<span class="br0">&#40;</span><span style="">15</span>,<span style="">0</span>,<span style="">160</span>,<span style="">140</span><span class="br0">&#41;</span>;
//Load the image object in JS, then apply to canvas onload
var myImage = new Image<span class="br0">&#40;</span><span class="br0">&#41;</span>;
myImage.onload = function<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
context.drawImage<span class="br0">&#40;</span>myImage, <span style="">30</span>, <span style="">15</span>, <span style="">130</span>, <span style="">110</span><span class="br0">&#41;</span>;
<span class="br0">&#125;</span>
myImage.src = &quot;cocktail.jpg&quot;;&lt;/code&gt;</pre></div></div>

<p>To make our portrait look like it&#8217;s hung on a wall, we&#8217;ll add a drop shadow and rotate the image slightly so it looks at a slight angle.</p>
<p>A drop shadow will need to be applied to the frame.</p>
<p><code>//Create a drop shadow<br />
context.shadowOffsetX = 10;<br />
context.shadowOffsetY = 10;<br />
context.shadowBlur = 10;<br />
context.shadowColor = "black";</code></p>
<p><a href="http://carsonified.com/wp-content/uploads/2009/08/cocktail-frame-shadow1.png"><img class="alignnone size-full wp-image-3059" title="cocktail-frame-shadow" src="http://carsonified.com/wp-content/uploads/2009/08/cocktail-frame-shadow1.png" alt="cocktail-frame-shadow" width="470" height="171" /></a></p>
<p><a href="http://www.ryancarson.com/uploads/canvas/portrait.html">Download the full source code of the portrait example</a></p>
<p>To rotate the canvas, we use the rotate() method which takes a value in radians to rotate the canvas by. This only applies rotation to subsequent drawing to the canvas, so make sure you&#8217;ve put this in the right place in your code.</p>
<p><code>//Rotate picture<br />
context.rotate(0.05);</code></p>
<p>This is what the finished frame looks like:</p>
<p><a href="http://carsonified.com/wp-content/uploads/2009/08/cocktail-rotated.png"><img class="alignnone size-full wp-image-3060" title="cocktail-rotated" src="http://carsonified.com/wp-content/uploads/2009/08/cocktail-rotated.png" alt="cocktail-rotated" width="470" height="176" /></a></p>
<p><a href="http://www.ryancarson.com/uploads/canvas/portrait.html">Download the full source code of the portrait example</a></p>
<h3>Animation and Physics</h3>
<p>Canvas drawings can be animated by repeatedly redrawing the canvas with different dimensions, positions or other values. With the use of JavaScript logic, you can also apply physics to your canvas objects as well.</p>
<p>Example uses:</p>
<ul>
<li><a href="http://www.efeion.com/canvastest/test.html">Bouncing Balls</a> by Efeion</li>
<li><a href="http://js-fireworks.appspot.com/">js-fireworks</a> by Kenneth Kufluk</li>
<li>Using canvas in conjunction with the HTML 5 audio element and a Twitter mashup to create the <a href="http://9elements.com/io/projects/html5/canvas/">HTML5 Canvas and Audio Experiment</a></li>
</ul>
<h3>Displaying Fancy Fonts</h3>
<p>Canvas can be used as a way of displaying non-standard fonts into a web page as an alternative to technologies like <a href="http://novemberborn.net/sifr3">sIFR</a>. The <a href="http://cufon.shoqolate.com/generate/">Cufon</a> project is one such implementation. Canvas-based font replacements like Cufon have advantages over sIFR, in that there are fewer resource overheads and no plug-in is required, however there are a few disadvantages:</p>
<ul>
<li>It generates lots of mark-up</li>
<li>Fonts are embedded, therefore it breaks the license terms of many fonts</li>
<li>Text can&#8217;t be selected</li>
</ul>
<p>Fonts need to be converted for use in Cufon using the tools on the <a href="http://cufon.shoqolate.com/generate/">Cufon homepage</a>.</p>
<h3>Letting Your Users do the Drawing</h3>
<p>JavaScript can interact with mouse and keyboard events, so you can create embedded drawing applications with canvas as the following examples demonstrate:</p>
<ul>
<li>Lightweight sketches with <a href="http://tinydoodle.appspot.com/">Tiny Doodle</a> by Andrew Mason</li>
<li>An <a href="http://canvaspaint.org/">MS paint clone in canvas</a> by Christopher Clay</li>
</ul>
<h3>Making up for Browser CSS Deficiencies</h3>
<p>Can&#8217;t wait for CSS3 support and want to add rounded corners, gradients or opacity without creating lots of images?  Projects like <a href="http://code.google.com/p/jqcanvas/">jqcanvas</a> add canvas tags behind standard HTML elements to add design to your web page.</p>
<h3>Browser Support</h3>
<p>The latest versions of Firefox, Safari, Chrome and Opera all enjoy reasonable to good support for Canvas.</p>
<p>What about Internet Explorer?</p>
<p>IE does not support canvas natively (as of IE8), however it has been given some compatibility thanks to the <a href="http://code.google.com/p/explorercanvas/">ExplorerCanvas</a> project and is simply a matter of including an extra JavaScript file before any canvas code in your page. You can hide it from other browsers in the standard way, using conditional comments.</p>
<p><code>&lt;!--[if IE]&gt;&lt;script src="excanvas.js"&gt;&lt;/script&gt;&lt;![endif]--&gt;</code></p>
<p>ExplorerCanvas even extends canvas support to IE6, although it&#8217;s not perfect so don&#8217;t expect it to render as well as modern browsers that support canvas natively.</p>
<h3>Accessibility</h3>
<p>Canvas isn&#8217;t currently thought of as accessible as there is no mark-up generated or API for textual content to be read. Fallback HTML can be added manually inside the canvas tag, but this will never be good enough to represent the canvas in an accessible way.</p>
<p>Thinking About HTML 5 Canvas Accessibility by Steve Faulkner explains the problems in more detail. There is now a general consensus that accessibility needs to be addressed which has lead to the Protocols and Formats Working Group at the W3C recently opening a discussion into <a href="http://lists.w3.org/Archives/Public/public-html/2009Jul/0562.html">proposals for adding accessibility for Canvas</a> with input from others.</p>
<h3>In Summary</h3>
<p>Although Canvas adds features to a page, I don&#8217;t think it has been particularly well thought out. In many ways it feels like a step into the past and represents a very old-fashioned way of drawing that is inferior to the modern XML-based SVG standard. It is pixel-based, as opposed to the nice vectors of SVG and to draw with it entails writing lots of unmanageable JavaScript. The lack of accessibility is also a big problem.</p>
<p>However, what Canvas has going for it, that SVG doesn&#8217;t, is that it can integrate with our existing web pages very easily. We can also work with canvas in much the same way we work with images in web pages.</p>
<p>By looking at the few examples in this article, we can get an idea of the variety of situations that Canvas can be applied to. Although the syntax may be frustrating, Canvas gives us drawing technology that we can use right away to enhance our pages.</p>
<p>Please give your thoughts, link to further examples or any feedback below.</p>
<h3>Further Reading</h3>
<ul>
<li><a href="http://lamberta.posterous.com/doodle-js">Doodle.js</a> &#8211; a nice library for working with canvas</li>
<li><a href="https://developer.mozilla.org/en/Canvas_tutorial">Canvas Tutorial</a> at Mozilla Developer Center</li>
<li><a href="http://dev.opera.com/articles/view/html-5-canvas-the-basics/">HTML 5 canvas &#8211; the basics</a> on the Opera Developer Community</li>
</ul>
<h3>Other Examples</h3>
<ul>
<li>Live photo editing with <a href="http://www.ernestdelgado.com/public-tests/canvasphoto/demo/canvas.html">Canvas Photo Demo</a></li>
<li><a href="https://developer.mozilla.org/En/Manipulating_video_using_canvas">Live video editing using canvas</a></li>
<li>Online office applications with <a href="http://bespin.mozilla.com/">Mozilla Bespin</a></li>
<li><a href="http://blog.nihilogic.dk/2008/04/super-mario-in-14kb-javascript.html">Super Mario Bros</a></li>
<li>Most of the <a href="http://www.chromeexperiments.com/">Chrome Experiments</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/how-to-draw-with-html-5-canvas/feed/</wfw:commentRss>
		<slash:comments>60</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 0.378 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-02-11 16:57:40 -->

