<?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>Unknown Kadath ( a blog about HTML5 )</title>
	<atom:link href="http://html5.litten.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://html5.litten.com</link>
	<description>HTML 5 Compliant Browser Required</description>
	<lastBuildDate>Sat, 21 Aug 2010 16:33:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>CSS3 Series: Multiple Columns</title>
		<link>http://html5.litten.com/css3-series-multiple-columns/</link>
		<comments>http://html5.litten.com/css3-series-multiple-columns/#comments</comments>
		<pubDate>Sat, 21 Aug 2010 16:32:37 +0000</pubDate>
		<dc:creator>James Litten</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[CSS 3.0]]></category>
		<category><![CDATA[css columns]]></category>

		<guid isPermaLink="false">http://html5.litten.com/?p=642</guid>
		<description><![CDATA[Even though this wonderful feature has been around for five years, it has yet to be implemented consistently across the major browsers. Hopefully, this will change soon. If you know a reason why this is so, please leave a comment. Thanks. The specification for CSS Multi-column Layout has 10 properties for CSS Multiple Columns. They [...]]]></description>
			<content:encoded><![CDATA[<p>Even though this wonderful feature has been around for five years, it has yet to be implemented consistently across the major browsers. Hopefully, this will change soon.<br />
If you know a reason why this is so, please leave a comment. Thanks.</p>
<p>The<a href="http://www.w3.org/TR/css3-multicol/"> specification for CSS Multi-column Layout</a> has 10 properties for CSS Multiple Columns.<br />
They are pretty self explanatory except for maybe &#8216;rule&#8217; which in this context means a vertical divider between the columns that behaves like a CSS border.<br />
<br />
column-width<br />
column-count<br />
columns (This is shorthand that can set either or both &#8216;width&#8217; and &#8216;count&#8217;)<br />
column-gap<br />
column-rule<br />
column-rule-width<br />
column-rule-style<br />
column-rule-color<br />
column-fill (Balances columns height)<br />
<br />
column-span (Allows for titles or headings to span across multiple or all columns)</p>
<h2>Browser Support</h2>
<p>Let&#8217;s look at the current implementations (as of August, 2010)<br /><br />
<strong>Mozilla (Firefox 3.6)</strong><br />
10 standard properties are supported plus <a href="https://developer.mozilla.org/en/CSS3_Columns#Height_Balancing">an extra one created by Mozilla</a><br />
-moz-column-height</p>
<p>-moz-column-width<br />
-moz-column-count<br />
-moz-columns<br />
-moz-column-gap<br />
-moz-column-rule<br />
-moz-column-rule-width<br />
-moz-column-rule-style<br />
-moz-column-rule-color<br />
-moz-column-fill<br />
-moz-column-span</p>
<p><strong>Webkit (Chrome 6, Safari 5)</strong><br />

10 standard properties are supported<br />
-webkit-column-width<br />
-webkit-column-count<br />
-webkit-columns<br />
-webkit-column-gap<br />
-webkit-column-rule<br />
-webkit-column-rule-width<br />
-webkit-column-rule-style<br />
-webkit-column-rule-color<br />
-webkit-column-fill<br />
-webkit-column-span</p>

<p><strong>Opera</strong><br />
Not Supported</p>
<p><strong>IE</strong><br />
Not Supported</p>
<h2>Webkit and Mozilla Render differently</h2>
<p>To further complicate the use of CSS3 multiple columns, even simple examples are rendered differently by Webkit and Mozilla.</p>
<p>If you set both column-width and column-count, visitors with a Webkit browser see a very different result than visitors with a Mozilla browser.<br />

For example, here are images of the following code in Firefox 3.6 and Chrome 6</p>
<p><code>-moz-column-count: 3;<br />
-moz-column-width: 45px;<br />
-webkit-column-count: 3;<br />
-webkit-column-width: 45px;</code></p>
<p><img src="http://html5.litten.com/wp-content/uploads/2010/08/ff.jpg" alt="" title="ff" width="599" height="211" class="alignnone size-full wp-image-647" /><br />
<img src="http://html5.litten.com/wp-content/uploads/2010/08/chr6.jpg" alt="" title="chr6" width="533" height="306" class="alignnone size-full wp-image-649" /></p>
<p>While Chrome limits the column width to what it is set at (45px) Firefox limits the column width based on the column number. If you allow Firefox to automatically set the column number, it will then limit the column width to what it is set at (45px).</p>
<p>It may be quite awhile before the average webmaster uses CSS3 multiple columns.</p>

<p>Some sites for further reading.<br />
W3C Specification <a href="http://www.w3.org/TR/css3-multicol/">http://www.w3.org/TR/css3-multicol/</a><br />
Demo page with source code. <a href="http://www.quirksmode.org/css/multicolumn.html">http://www.quirksmode.org/css/multicolumn.html</a><br />
Mozilla Dev Page <a href="https://developer.mozilla.org/en/CSS3_Columns">https://developer.mozilla.org/en/CSS3_Columns</a>]]></content:encoded>
			<wfw:commentRss>http://html5.litten.com/css3-series-multiple-columns/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Graphing Data in the HTML5 Canvas Element Part IV Simple Pie Charts</title>
		<link>http://html5.litten.com/graphing-data-in-the-html5-canvas-element-part-iv-simple-pie-charts/</link>
		<comments>http://html5.litten.com/graphing-data-in-the-html5-canvas-element-part-iv-simple-pie-charts/#comments</comments>
		<pubDate>Wed, 04 Aug 2010 19:57:19 +0000</pubDate>
		<dc:creator>James Litten</dc:creator>
				<category><![CDATA[Canvas Element]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[2d context]]></category>
		<category><![CDATA[graphing]]></category>
		<category><![CDATA[pie charts]]></category>

		<guid isPermaLink="false">http://html5.litten.com/?p=614</guid>
		<description><![CDATA[In this post we will create a simple pie chart that is easy to feed data to. This example is coded for readability and not for optimized operation. All you need is a text editor like notepad and an HTML5 friendly browser (I&#8217;m using Firefox 3.6). &#60;!doctype html&#62; &#60;html&#62; &#60;head&#62; &#60;meta charset="UTF-8" /&#62; &#60;title&#62;Canvas Test&#60;/title&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>In this post we will create a simple pie chart that is easy to feed data to.</p>

<p>This example is coded for readability and not for optimized operation. All you need is a text editor like notepad and an HTML5 friendly browser (I&#8217;m using Firefox 3.6).</p>
<pre><code>
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset="UTF-8" /&gt;
&lt;title&gt;Canvas Test&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;section&gt;
&lt;div&gt;
&lt;canvas id="canvas" width="400" height="300"&gt;
This text is displayed if your browser does not support HTML5 Canvas.
&lt;/canvas&gt;
&lt;/div&gt;

&lt;script type="text/javascript"&gt;

var myColor = ["#ECD078","#D95B43","#C02942","#542437","#53777A"];
var myData = [10,30,20,60,40];

function getTotal(){
var myTotal = 0;
for (var j = 0; j &lt; myData.length; j++) {
myTotal += (typeof myData[j] == 'number') ? myData[j] : 0;
}
return myTotal;
}

function plotData() {
var canvas;
var ctx;
var lastend = 0;
var myTotal = getTotal();

canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);

for (var i = 0; i &lt; myData.length; i++) {
ctx.fillStyle = myColor[i];
ctx.beginPath();
ctx.moveTo(200,150);
ctx.arc(200,150,150,lastend,lastend+
  (Math.PI*2*(myData[i]/myTotal)),false);
ctx.lineTo(200,150);
ctx.fill();
lastend += Math.PI*2*(myData[i]/myTotal);
}
}

plotData();

&lt;/script&gt;
&lt;/section&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre></code>
<p>You can copy this code and paste it into a new file called something like simplepie.html and when you open it with an HTML5 friendly browser like Firefox 3.6 it will display the pie chart.</p>
<span id="more-614"></span>
<p><strong>Here is our canvas in action...</strong></p>
  <section>    
    <div>
        <canvas id="canvas" width="400" height="300">
         This text is displayed if your browser does not support HTML5 Canvas.
        </canvas>
    </div>
    
<script type="text/javascript">

var myColor = ["#ECD078","#D95B43","#C02942","#542437","#53777A"];
var myData = [10,30,20,60,40];

function getTotal(){
  var myTotal = 0;  
  for (var j = 0; j < myData.length; j++) {
    myTotal += (typeof myData[j] == 'number') ? myData[j] : 0;
  }
  return myTotal;
}

function plotData() {
  var canvas;  
  var ctx;
  var lastend = 0;
  var myTotal = getTotal();

  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");  
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  for (var i = 0; i < myData.length; i++) {
    ctx.fillStyle = myColor[i];
    ctx.beginPath();
    ctx.moveTo(200,150);    
    ctx.arc(200,150,150,lastend,lastend+(Math.PI*2*(myData[i]/myTotal)),false);
    ctx.lineTo(200,150);
    ctx.fill();
    lastend += Math.PI*2*(myData[i]/myTotal);      
  }
}

plotData();

</script>
  </section>
<br/>
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<p><strong>The algorithm for making a simple pie chart is something like this...</strong></p>

<ol style="font-weight: bold;">
	<li><div style="font-weight: normal;">Get the data that is being represented by the chart (it must be numerical)</div></li>

	<li><div style="font-weight: normal;">Calculate the total by adding all of the data together.</div></li>

	<li><div style="font-weight: normal;">Calculate the amount of pie for each piece of data by dividing it by the total.</div></li>

	<li><div style="font-weight: normal;">Multiply 2*pi radians by the amount of pie to get the length of the arc for that piece of pie.</div></li>

	<li><div style="font-weight: normal;">Draw the resulting arcs at a distance of r (the radius) from the center starting each arc at either 0 (the first arc) or from the end of the last drawn arc.</div></li>

	<li><div style="font-weight: normal;">Each arc has a line from its beginning and its ending to the center of the circle that is of length r</div></li>
</ol>
</div>
<br/>

<p>Since the arc() method of the 2d canvas context is based on paths, this is real easy to code.</p>
<blockquote>
<pre>arc(x, y, radius, startAngle, endAngle, anticlockwise)</pre>
<p><em>This method takes five parameters: x and y are the coordinates of the circle's center. Radius is self explanatory. The startAngle and endAngle parameters define the start and end points of the arc in radians. The starting and closing angle are measured from the x axis. The anticlockwise parameter is a Boolean value which when true draws the arc anticlockwise, otherwise in a clockwise direction.<br/>
Note: Angles in the arc function are measured in radians, not degrees. To convert degrees to radians you can use the following JavaScript expression: var radians = (Math.PI/180)*degrees.<br/>
<a href="https://developer.mozilla.org/en/Canvas_tutorial/Drawing_shapes#Arcs">https://developer.mozilla.org/en/Canvas_tutorial/Drawing_shapes#Arcs</a></em></p>
</blockquote>
<br/>
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<p>Step 1 of the algorithm is accomplished by this loop in our <code>plotData()</code> function <br/>
   <pre>for (var i = 0; i < myData.length; i++) {</pre>
<br/>
Where myData[i] represents the data from the hard coded global variable <br/>
    <pre>var myData = [10,30,20,60,40];</pre>
<br/>
This could easily be from a database, table data or from input textboxes filled in by the visitor.</p>
</div>
<br/>


<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<p>Step 2 of the algorithm is accomplished by our <code>getTotal()</code> function which loops through our data and adds it all together returning our total. It also verifies that our data is numeric giving it a value of zero if it is not.
<pre>function getTotal(){
  var myTotal = 0;  
  for (var j = 0; j < myData.length; j++) {
    myTotal += (typeof myData[j] == 'number') ? myData[j] : 0;
  }
  return myTotal;
}      
</pre>
</p>
</div>
<br/>

<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<p>Step 3 of the algorithm is accomplished by the highlighted part of this line in our <code>plotData()</code> function.
    <pre>ctx.arc(200,150,150,lastend,lastend+
       (Math.PI*2*<span style="background-color:yellow">(myData[i]/myTotal)</span>),false);</pre>
</p>
</div>
<br/>
    
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">    
<p>Step 4 of the algorithm is accomplished by the highlighted part of this line in our <code>plotData()</code> function.
    <pre>ctx.arc(200,150,150,lastend,lastend+
       <span style="background-color:yellow">(Math.PI*2*(myData[i]/myTotal))</span>,false);</pre>    
</p>
</div>
<br/>
    
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">    
<p>Step 5 of the algorithm is accomplished in our <code>plotData()</code> function by using the variable lastend to start at 0 radians and then keep track of where the previous arc ended.
    <pre>lastend += Math.PI*2*(myData[i]/myTotal);</pre> 
</p>
</div>
<br/>    
    
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">    
<p>Step 6 of the algorithm is accomplished in our <code>plotData()</code> function by starting our path at the center of the circle
<pre>    ctx.beginPath();
    ctx.moveTo(200,150);</pre>
    
then we draw our arc which extends our path from the center to the start of our arc        
<pre>    ctx.arc(200,150,150,lastend,lastend+
       (Math.PI*2*(myData[i]/myTotal)),false);</pre>

then we extend our path back to the center of our circle and fill in the shape (our pie slice)    
<pre>    ctx.lineTo(200,150);
    ctx.fill(); </pre>
</p>
</div>
<br/>


<p>Since we use an array of color values to make sure that all the pie slices are easy to see,
<pre>    var myColor = ["#ECD078","#D95B43","#C02942","#542437","#53777A"]; </pre>
we can create a legend saying what each color represents.</p> 

<table border="0" cellpadding="10">
<tbody>
<tr><td align="center" style="color: #ECD078;">&#9608;</td>
<td align="center">10</td></tr>
<tr><td align="center" style="color: #D95B43;">&#9608;</td>
<td align="center">30</td></tr>
<tr><td align="center" style="color: #C02942;">&#9608;</td>
<td align="center">20</td></tr>
<tr><td align="center" style="color: #542437;">&#9608;</td>
<td align="center">60</td></tr>
<tr><td align="center" style="color: #53777A;">&#9608;</td>
<td align="center">40</td></tr>
</tbody>
</table>
<br/>



<p>In our next post, we'll look at making our pie fancy with labels and maybe a few animations. </p>

<p>This is post 4 of a multipart series of posts.</p>
<p><a href="http://html5.litten.com/graphing-data-in-the-html5-canvas-element-part-i/">Graphing Data in the HTML5 Canvas Element Part I</a></p> 
<p><a href="http://html5.litten.com/graphing-data-in-the-html5-canvas-element-part-ii/">Graphing Data in the HTML5 Canvas Element Part II</a></p>
<p><a href="http://html5.litten.com/graphing-data-in-the-html5-canvas-element-part-iii/">Graphing Data in the HTML5 Canvas Element Part III</a></p>


]]></content:encoded>
			<wfw:commentRss>http://html5.litten.com/graphing-data-in-the-html5-canvas-element-part-iv-simple-pie-charts/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>HTML5 Web Storage, Using localStorage and sessionStorage Objects</title>
		<link>http://html5.litten.com/html5-web-storage-using-localstorage-and-sessionstorage-objects/</link>
		<comments>http://html5.litten.com/html5-web-storage-using-localstorage-and-sessionstorage-objects/#comments</comments>
		<pubDate>Tue, 03 Aug 2010 21:17:33 +0000</pubDate>
		<dc:creator>James Litten</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Web Storage]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[localStorage]]></category>
		<category><![CDATA[sessionStorage]]></category>
		<category><![CDATA[webstorage]]></category>

		<guid isPermaLink="false">http://html5.litten.com/?p=583</guid>
		<description><![CDATA[Web storage started as part of the HTML5 spec for storing key-value pair data in web clients. It now has its own spec. There are other plans for storing databases that are structured and can be queried using SQL which are handled in a separate spec . Seeing the need for storing more key-value pair [...]]]></description>
			<content:encoded><![CDATA[<p>Web storage started as part of the HTML5 spec for storing key-value pair data in web clients. It now has <a href="http://www.w3.org/TR/webstorage/">its own spec</a>. There are other plans for storing databases that are structured and can be queried using SQL which are handled in a <a href="http://www.w3.org/TR/webdatabase/">separate spec</a> .</p>
<p>Seeing the need for storing more key-value pair data on the web client than can currently be stored in a cookie, all major web browsers quickly adopted support for a storage object that can hold up to 5MB of data that persists until the web client&#8217;s cache is cleared or the storage object is programatically cleared, or in the case of sessionStorage, the browser window (tab) is closed.
This quick and relatively consistent adoption by web browsers is a rare treat for web developers.</p> 

<div style=" 
background-color: #CCC;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<p><strong>IMPORTANT: Do not store sensitive data in web storage. When I do penetration testing, locally stored data is one of the first things that I look at.</strong></p>
</div><br/>

<div style=" 
background-color: #CCC;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<p><strong>IMPORTANT: All data in web storage is stored as strings. If you want to store an object, you should use JSON and call stringify() on it before storing it and parse() on it after retrieving it.</strong></p>
</div><br/>
<p>There are two flavors of the storage object that we will be looking at.</p>

<h3>sessionStorage object</h3>
<p>The sessionStorage object stores data only for a session, meaning that the data is stored until the browser (or tab) is closed. it is not available when a file is run locally.</p>

<p>Data stored in the sessionStorage object is accessible only from the page that initially stored the data.</p>

<h3>localStorage object</h3>
<p>Data stored using the localStorage object is persisted until it is specifically removed via JavaScript or the user clears the browser&#8217;s cache.</p>

<p>Data stored in the localStorage object is accessible only from the domain that initially stored the data.</p>
<hr />
<p>Both localStorage and sessionStorage objects have the same interface, differing only in how the data stored by them persists and who can access the data.</p>

<div style=" 
background-color: #CCC;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<h3>The setItem method</h3>
<pre>setItem( key, value)
sessionStorage.setItem("name", "Sam")
localStorage.setItem("name", "Sam")

or the property using an <a href="http://en.wiktionary.org/wiki/expando">expando</a>
sessionStorage.name("Sam")
localStorage.name("Sam")
</pre>
</div><br/>
<div style=" 
background-color: #CCC;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<h3>The getItem method</h3>

<pre>getItem(key)
name = sessionStorage.getItem("name")
name = localStorage.getItem("name")

or the property using an expando
name = sessionStorage.name
name = localStorage.name
</pre>
</div><br/>
<div style=" 
background-color: #CCC;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<h3>The removeItem method</h3>

<pre>removeItem(key)
name = sessionStorage.removeItem("name")
name = localStorage.removeItem("name")

</pre>
<p>The property using an expando required an extra &#8216;delete&#8217; keyword and is no longer in the spec.</p> 
</div><br/>
<div style=" 
background-color: #CCC;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<h3>The clear method</h3>
<p>The clear() method causes the list associated with the object to be emptied of all key/value pairs</p>

<pre>sessionStorage.clear
localStorage.clear
</pre>

</div><br/>
<div style=" 
background-color: #CCC;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<h3>The key and length properties</h3>
<p>Key and length are useful for looping through all of the key value pairs, especially if you don&#8217;t know what they all are.</p>
Key is an index of the key values ( key(0), key(1), key(2) &#8230;)
Length is the number of keys.

<pre>
for (var i=0, len = sessionStorage.length; i  <  len; i++){
    var key = sessionStorage.key(i);
    var value = sessionStorage.getItem(key);
    alert(key + "=" + value);
} 
</pre>

</div><br/>
<h3>Storage Event</h3>
<p>The storage event is fired on the window object whenever something changes in storage. For example, if you set an item to its existing value or call clear() when there are no named keys, the storage event will not fire, because nothing actually changed in the storage area.</p>

<p>The storage event has the following attributes</p>
<ul>
<li><strong>key</strong> the named key that was added, removed, or modified</li>

<li><strong>oldValue</strong> the previous value (now overwritten), or null if a 
   new item was added</li>

<li><strong>newValue</strong> any the new value, or null if an item was removed</li>

<li><strong>url</strong> the page which called a method that triggered this change</li>

<li><strong>storageArea</strong> represents the Storage object that was affected.</li>
</ul>
<h3>Some online DEMOs</h3>
<p><a href="http://html5demos.com/storage">HTML5 Demos: Storage</a><br/>
<a href="http://people.opera.com/shwetankd/external/demos/webstorage_demo.htm">Web Storage Example</a></p>
<h3>Browser Compatibility (as of August, 2010)</h3>
<pre>
Internet Explorer 8
Firefox 3.5 
Safari 4
Google Chrome 5
Opera 10.50
</pre>
<p>Only Opera supports the Storage event's attributes but I've verified that the storage event can be triggered on Chrome 5 and Firefox 3.6 though, the attributes for the event are all set to undefined.</p>
<h3>Further Reading</h3>
<p><a href="http://www.amazon.com/dp/047022780X?tag=allcrafts&#038;camp=213381&#038;creative=390973&#038;linkCode=as4&#038;creativeASIN=047022780X&#038;adid=09BTD55PR43DYE1F7JEH&#038;">Professional JavaScript for Web Developers</a> Chapter Chapter 19 section on DOM Storage</p>
<p><a href="http://www.amazon.com/gp/product/0321687299?ie=UTF8&#038;tag=allcrafts&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=0321687299">Introducing HTML5</a>  Chapter 6</p>
<hr />]]></content:encoded>
			<wfw:commentRss>http://html5.litten.com/html5-web-storage-using-localstorage-and-sessionstorage-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Playing With CSS Transitions On Firefox 4 Beta 2</title>
		<link>http://html5.litten.com/playing-with-css-transitions-on-firefox-4-beta-2/</link>
		<comments>http://html5.litten.com/playing-with-css-transitions-on-firefox-4-beta-2/#comments</comments>
		<pubDate>Thu, 29 Jul 2010 18:31:26 +0000</pubDate>
		<dc:creator>James Litten</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[CSS 3.0]]></category>
		<category><![CDATA[transitions]]></category>

		<guid isPermaLink="false">http://html5.litten.com/?p=578</guid>
		<description><![CDATA[I saw the recent announcement by Paul Rouget that Firefox 4 beta 2 has support for CSS transitions and I thought it would be fun to play with it. Here is a demo with complete source code where I chained together a bunch of CSS transitions using the transitionend event to trigger the transitions sequentially. [...]]]></description>
			<content:encoded><![CDATA[<p>I saw the <a href="http://hacks.mozilla.org/2010/07/firefox4-beta2/">recent announcement by Paul Rouget</a> that Firefox 4 beta 2 has support for CSS transitions and I thought it would be fun to play with it.</p>
<p>Here is a demo with complete source code where I chained together a bunch of CSS transitions using the transitionend event to trigger the transitions sequentially.</p>
<p><a href="http://html5.litten.com/csstransitions/csstransitionsdemo.html">DEMO CSS transitions in Firefox 4 beta 2</a></p>
<p>The demo requires <a href="http://www.mozilla.com/en-US/firefox/beta/">Firefox 4 beta 2</a></p>
<p>I found that the transitionend event was triggered more often then I expected and had to remove listeners for the event when I was done with them or they sometimes triggered again. I need to learn more about what triggers them. </p>
<p>Have fun with the code as that is the best way to learn.</p>]]></content:encoded>
			<wfw:commentRss>http://html5.litten.com/playing-with-css-transitions-on-firefox-4-beta-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Multiple HTML5 Canvases as Layers</title>
		<link>http://html5.litten.com/using-multiple-html5-canvases-as-layers/</link>
		<comments>http://html5.litten.com/using-multiple-html5-canvases-as-layers/#comments</comments>
		<pubDate>Mon, 26 Jul 2010 21:28:25 +0000</pubDate>
		<dc:creator>James Litten</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[Canvas Element]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[2d context]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[CSS 3.0]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[restore]]></category>
		<category><![CDATA[save]]></category>

		<guid isPermaLink="false">http://html5.litten.com/?p=559</guid>
		<description><![CDATA[DEMO Here&#8217;s our finished canvas with full source code. The reasons why you would want to layer multiple canvases on top of each other are many but they all have a common root. There is a requirement in the W3C definition of the 2d context&#8230; There is only one CanvasRenderingContext2D object per canvas, so calling [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://html5.litten.com/layers/canvaslayers.html"><strong>DEMO</strong> Here&#8217;s our finished canvas with full source code.</a></p>

<p>The reasons why you would want to layer multiple canvases on top of each other are many but they all have a common root. There is a requirement in the W3C definition of the 2d context&#8230; </p> 

<blockquote><em>There is only one CanvasRenderingContext2D  object per canvas, so calling the getContext()  method with the 2d  argument a second time must return the same object. <br/>
<a href="http://dev.w3.org/html5/2dcontext/#conformance-requirements">http://dev.w3.org/html5/2dcontext/#conformance-requirements</a></em>
</blockquote>

<p>Having just one 2d context means that you have to keep track of everything on the context even if you only want to change part of the canvas.</p> 

<p>An example of using layers is animation. When I was a child, I loved making animated cartoons and I learned that if I painted them on clear plastic sheets I could stack the sheets and only redraw the parts that moved. I could make an elaborate background and use it over and over instead of redrawing it for every frame. The same principle applies here to our canvases.</p>

<p>In this example, our three canvases have transparent areas that allow you to see what is on the canvas beneath each.</p>
<span id="more-559"></span>
<p>First, let&#8217;s look at our three canvases separately and then we&#8217;ll stack them on top of each other.</p>

  <section>
  <div>
  <p>Our bottom layer</p>
    <canvas id="layer1" height="300px" width="400">
      This text is displayed if your browser does not support HTML5 Canvas.
    </canvas>
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<pre><code>
function draw1() {
  ctx1.clearRect(0, 0, WIDTH, HEIGHT);
  ctx1.fillStyle = "#FAF7F8";
  ctx1.beginPath();
  ctx1.rect(0,0,WIDTH,HEIGHT);
  ctx1.closePath();
  ctx1.fill();
  ctx1.fillStyle = "#444444";
  ctx1.beginPath();
  ctx1.arc(x, y, 10, 0, Math.PI*2, true);
  ctx1.closePath();
  ctx1.fill();

  if (x + dx &gt; WIDTH || x + dx &lt; 0)
    dx = -dx;
  if (y + dy &gt; HEIGHT || y + dy &lt; 0)
    dy = -dy;

  x += dx;
  y += dy;
}
</code></pre> 
<p>The code for this animation is fully explained here. <a href="http://html5.litten.com/simple-animation-in-the-html5-canvas-element/">Simple Animation in the HTML5 Canvas Element</a> </p>
</div>
    </div>
      <div>
  <p>Our middle layer</p>
    <canvas id="layer2" height="300px" width="400">
      This text is displayed if your browser does not support HTML5 Canvas.
    </canvas>
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<pre><code>
function draw2() {
  ctx2.clearRect(0, 0, WIDTH, HEIGHT);
  ctx2.drawImage(city, 0, 0); 
}
</code></pre> 
<p>We are simply drawing city.png <a href="http://html5.litten.com/layers/city.png">http://html5.litten.com/layers/city.png</a> to the canvas. The sky in this image is transparent.</p>
</div>    
    </div>
      <div>
  <p>Our top layer</p>
    <canvas id="layer3" height="300px" width="400">
      This text is displayed if your browser does not support HTML5 Canvas.
    </canvas>
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<pre><code>
function draw3() {
  ctx3.clearRect(0, 0, WIDTH, HEIGHT);
  ctx3.fillStyle = "#444444";
  ctx3.save();
  ctx3.translate(200,200);
  ctx3.rotate(x/20); 
  ctx3.fillRect(-15, -15, 30, 30);  
  ctx3.restore();
}
</code></pre> 
<p>Here we transform the canvas&#8217;s coordinate system and rotate the square based on the global variable x which is used in layer 1 also. For more information on transforms with save() and restore() go here <a href="http://html5.litten.com/understanding-save-and-restore-for-the-canvas-context/">Understanding save() and restore() for the Canvas Context</a> </p>
</div>
  </div>
<script type="text/javascript">
var layer1;
var layer2;
var layer3;  
var ctx1;
var ctx2;
var ctx3;
var x = 400;
var y = 300;
var dx = 2;
var dy = 4;
var WIDTH = 400;
var HEIGHT = 300; 
var city = new Image();

function init() {
  city.src ="http://html5.litten.com/layers/city.png";
  layer1 = document.getElementById("layer1");
  ctx1 = layer1.getContext("2d");
  layer2 = document.getElementById("layer2");
  ctx2 = layer2.getContext("2d");
  layer3 = document.getElementById("layer3");
  ctx3 = layer3.getContext("2d");
  setInterval(drawAll, 20);
}

function drawAll() {
  draw1();
  draw2();
  draw3();
}

function draw1() {
  ctx1.clearRect(0, 0, WIDTH, HEIGHT);
  ctx1.fillStyle = "#FAF7F8";
  ctx1.beginPath();
  ctx1.rect(0,0,WIDTH,HEIGHT);
  ctx1.closePath();
  ctx1.fill();
  ctx1.fillStyle = "#444444";
  ctx1.beginPath();
  ctx1.arc(x, y, 10, 0, Math.PI*2, true);
  ctx1.closePath();
  ctx1.fill();

  if (x + dx > WIDTH || x + dx < 0)
    dx = -dx;
  if (y + dy > HEIGHT || y + dy < 0)
    dy = -dy;

  x += dx;
  y += dy;
}

function draw2() {
  ctx2.clearRect(0, 0, WIDTH, HEIGHT);
  ctx2.drawImage(city, 0, 0);   
}

function draw3() {
  ctx3.clearRect(0, 0, WIDTH, HEIGHT);
  ctx3.fillStyle = "#444444";
  ctx3.save();
  ctx3.translate(200,200);
  ctx3.rotate(x/20); 
  ctx3.fillRect(-15, -15, 30, 30);  
  ctx3.restore();
}

init();
</script>
  </section>

<h3>Now to stack them</h3>
<p>We use CSS to set all the canvases to an absolute position of (0,0) inside our parent DIV tag.</p>
<pre><code>
    position:absolute;
    left:0px;
    top:0px;
</code></pre>     
<p>We also use CSS to set the z-index of our canvases. The z-index property specifies the stack order of an element. Items with lower z-index values go behind items with higher z-index values.</p>
<pre><code>
<strong>Bottom layer</strong>
    canvas id="layer1" 
    style="z-index: 1;
    
<strong>Middle layer</strong>    
    canvas id="layer2" 
    style="z-index: 2;

<strong>Top Layer </strong>   
    canvas id="layer3" 
    style="z-index: 3;      
</code></pre>     
<p><a href="http://html5.litten.com/layers/canvaslayers.html"><strong>DEMO</strong> Here's our finished canvas with full source code.</a></p>

<p>Now it doesn't matter that a canvas can only have one 2d context because we can just make multiple canvases and stack them.</p>

<p>If you have a question that you do not want published as a public comment, then use my <a href="http://html5.litten.com/contact-me/">contact page</a>. </p>

<p>Have fun with the code as that is the easiest way to learn.</p>      ]]></content:encoded>
			<wfw:commentRss>http://html5.litten.com/using-multiple-html5-canvases-as-layers/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>IE Compatible Canvas Drag and Drop With jQuery and ExCanvas</title>
		<link>http://html5.litten.com/ie-compatible-canvas-drag-and-drop-with-jquery-and-excanvas/</link>
		<comments>http://html5.litten.com/ie-compatible-canvas-drag-and-drop-with-jquery-and-excanvas/#comments</comments>
		<pubDate>Tue, 20 Jul 2010 18:25:01 +0000</pubDate>
		<dc:creator>James Litten</dc:creator>
				<category><![CDATA[Canvas Element]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://html5.litten.com/?p=538</guid>
		<description><![CDATA[This post is about making drag and drop work on a canvas in Internet Explorer versions 6, 7 and 8 . The details of how to drag and drop on the canvas can be found in this previous post. How to Drag and Drop on an HTML5 Canvas To modify our canvas in order to [...]]]></description>
			<content:encoded><![CDATA[<p>This post is about making drag and drop work on a canvas in Internet Explorer versions 6, 7 and 8 . The details of how to drag and drop on the canvas can be found in this previous post.
<a href="http://html5.litten.com/how-to-drag-and-drop-on-an-html5-canvas/">How to Drag and Drop on an HTML5 Canvas</a>  </p>


<h3>To modify our canvas in order to make it work in IE we need to &#8230;</h3>
<strong><ul>
<li>Use ExplorerCanvas to make IE&#8217;s VML act like a canvas like object</li>

<li>Use jQuery to manage our events and make them compatible with IE</li>

<li>Use jQuery to calculate our canvas&#8217; offsets</li>

<li>Move our call to <code>init()</code> to the body.onload event</li>
</ul></strong>
<p>Sounds like a lot but it really isn&#8217;t.</p> 

<p><a href="http://html5.litten.com/dragdrop/dragdropie.html">Here&#8217;s the DEMO page that should work in all current browsers including IE</a>. The full source code for the page is listed below the canvas.</p>

<span id="more-538"></span>

<h3>Use ExplorerCanvas to make IE&#8217;s VML act like a canvas like object</h3>
<p>In our &lt;head&gt; we add a conditional reference to Google&#8217;s Explorer Canvas javascript framework so that it loads if the visitor is using IE.</p>
<pre><code>
&lt;!--[if IE]&gt;&lt;script type="text/javascript" src="excanvas.js"&gt;&lt;/script&gt;
&lt;![endif]--&gt;
</code></pre>
<p>The file excanvas.js can be downloaded from here&#8230; </p>
<a href="http://code.google.com/p/explorercanvas/downloads/list">http://code.google.com/p/explorercanvas/downloads/list</a>

<h3>Use jQuery to manage our events and make them compatible with IE</h3>
<p>The jQuery framework does a great job of handling events across browsers. It is the main reason that I have used jQuery in my own projects. You do not even have to download it as it is hosted by Google at.<br/>
http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js <br/>
So simply adding a reference to it in your &lt;head&gt; is enough to use it.</p>
<pre><code>
&lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs
/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
</code></pre>
<p>If you want to have it on your server, you can download it from here.<br/>
<a href="http://jquery.com/">http://jquery.com/</a> </p>

<p>Setting our event listener is a little different but we still use the same functions that we wrote in the original post <a href="http://html5.litten.com/how-to-drag-and-drop-on-an-html5-canvas/">How to Drag and Drop on an HTML5 Canvas</a>.</p>
<pre><code>
 $("canvas").mousedown(function myDown(e){
 var position = $("canvas").position();
 if (e.clientX < x + 15 + position.left &#038;&#038; e.clientX > x - 15 + 
  position.left &#038;&#038; e.clientY < y + 15 + position.top &#038;&#038; 
  e.clientY > y -15 + position.top){
    x = e.clientX;
    y = e.clientY;
    dragok = true;
    $("canvas").mousemove(function myMove(e){
       if (dragok){
        x = e.clientX - position.left;
        y = e.clientY - position.top;
       }
});
 }
}); 
 $("canvas").mouseup(function myUp(e){
  dragok = false;
  $("canvas").mousemove(null);
}); 
</code></pre>
<p>Notice that we removed our traditional event listeners and wrapped the functions our events trigger with the jQuery event listeners</p>
<pre><code>
$("canvas").mousedown()
$("canvas").mouseup()
$("canvas").mousemove()
</code></pre>
<p>These are shorthand versions of the jQuery bind method. The longhand looks like this.</p>
<pre><code>
$("canvas").bind(mousemove, mymove())
</code></pre>
<p>The shorthand versions work fine and are easier to read.</p>


<h3>Use jQuery to calculate our canvas&#8217; offsets</h3>
<p>Sometimes I feel as though offsets are the bane of my existence. jQuery makes them consistent across browsers with the position method.<br/>
The position method returns an object containing the position of the top-left corner of the element relative to the top-left corner of the first positioned parent of the element.<br/>
In our <code>myDown(e)</code> function we get our canvas&#8217; offsets with regard to their parent. </p>
<pre><code>
var position = $("canvas").position();
</code></pre>
<p>Now we can use <code>position.left</code> and <code>position.top</code> as our offsets in calculating where our mouse is on the canvas. </p>
<pre><code>
       if (dragok){
        x = e.clientX - position.left;
        y = e.clientY - position.top;
       }
</code></pre>       
<h3>Move our call to init() to the body.onload event</h3>
<p>That&#8217;s all we have left to do.</p>
<pre><code>
&lt;body onload = "init();"&gt;
</code></pre>
<p>This makes sure that <code>init()</code> isn&#8217;t called until the &lt;canvas&gt; is properly loaded in ExplorerCanvas.</p>

<p>That&#8217;s it. <a href="http://html5.litten.com/dragdrop/dragdropie.html">Here is the full source code of our modified canvas as well as a DEMO</a>.</p>

<p>If you have a question that you do not want published as a public comment, then use my <a href="http://html5.litten.com/contact-me/">contact page</a>. </p>]]></content:encoded>
			<wfw:commentRss>http://html5.litten.com/ie-compatible-canvas-drag-and-drop-with-jquery-and-excanvas/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Slicing Spritemaps and Parallax Scrolling on the HTML5 Canvas</title>
		<link>http://html5.litten.com/slicing-spritemaps-and-parallax-scrolling-on-the-html5-canvas/</link>
		<comments>http://html5.litten.com/slicing-spritemaps-and-parallax-scrolling-on-the-html5-canvas/#comments</comments>
		<pubDate>Fri, 16 Jul 2010 17:58:56 +0000</pubDate>
		<dc:creator>James Litten</dc:creator>
				<category><![CDATA[Canvas Element]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[2d context]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[drawimage]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://html5.litten.com/?p=504</guid>
		<description><![CDATA[In this example we will look at slicing images with the drawImage() method of a 2d canvas context. We&#8217;ll use two images that are larger than the canvas to create a parallax scrolling effect that is common in 2d games and also another image as a spritemap consisting of three sprites to show how to [...]]]></description>
			<content:encoded><![CDATA[<p>In this example we will look at slicing images with the <code>drawImage()</code> method of a 2d canvas context. We&#8217;ll use two images that are larger than the canvas to create a parallax scrolling effect that is common in 2d games and also another image as a spritemap consisting of three sprites to show how to slice out and draw individual sprites.</p>

<p>I made this example as simple as possible to keep from cluttering up the key concepts of slicing and drawing pieces of images on the canvas. It only moves in one direction by pressing the right arrow key on your keyboard.</p> 
<span id="more-504"></span>
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<strong>Contents</strong>
<ul>
<li><a href="#whatyouneed">What you need to run this</a></li>
<li><a href="#thegame">Here&#8217;s the canvas (you need an HTML5 friendly browser to view this)</a></li>
<li><a href="#thecode">Here&#8217;s the code</a></li>
<li><a href="#makeimage">Making the images</a></li>
<li><a href="#moving">Slicing and moving the images</a></li>
<li><a href="#fromhere">Where to go from here</a></li>
</ul>
</div>
<br/>
<h3><a name="whatyouneed"></a>What you need to run this</h3>
<ul>
<li>An HTML5 friendly browser. I use <a href="http://www.google.com/chrome">Google Chrome</a>  and <a href="http://www.mozilla.com/en-US/firefox/personal.html">Firefox 3.6</a> .</li>
<li>A text editor like Notepad. I use <a href="http://www.pspad.com/en/">PSPad</a>  </li>
<li>Right click and save the three images below to the same directory that you put your HTML page in.</li>
</ul>

<p>This looks empty but it is white stars on a transparent background so right click and you can save it.</p>
<img src="http://html5.litten.com/wp-content/uploads/2010/07/sky.png" alt="" title="sky" width="600" height="300" class="alignnone size-full wp-image-511" />
<p>sky.png</p>

<img src="http://html5.litten.com/wp-content/uploads/2010/07/city.png" alt="" title="city" width="600" height="300" class="alignnone size-full wp-image-513" />
<p>city.png</p>

<img src="http://html5.litten.com/wp-content/uploads/2010/07/ufo.png" alt="" title="ufo" width="96" height="32" class="alignnone size-full wp-image-515" />
<p>ufo.png</p>
<h3><a name="thegame"></a>Here&#8217;s the canvas (you need an HTML5 friendly browser to view this)</h3>
<p>Press the right arrow key on your keyboard to move the spaceship. We only have it coded for one key to keep it simple. Once you understand how it works, it is easy to add movement in other directions.</p>

<section>
    
    <div>
        <canvas id="canvas" width="300" height="300">
         This text is displayed if your browser does not support HTML5 Canvas.
        </canvas>
    </div>

<script type="text/javascript">
var canvas;             // Canvas object
var ctx;                // 2d Context object
var WIDTH = 300;        // Canvas width
var HEIGHT = 300;       // Canvas height
var sky = new Image();  // Sky image
var skydx = 2;          // Amount to move sky image
var skyx = 0;           // x coord to slice sky image
var city = new Image(); // City image
var citydx = 5;         // Amount to move city image
var cityx = 0;          // x coord to slice city image
var ufo = new Image();  // UFO image
var ufox = 150;         // x coord of UFO image
var ufoy = 250;         // y coord of UFO image
var ufosprite = 0;      // x coord to slice UFO image

function rect(x,y,w,h) {
  ctx.beginPath();
  ctx.rect(x,y,w,h);
  ctx.closePath();
  ctx.fill();
  ctx.stroke();
}

function clear() {
  ctx.clearRect(0, 0, WIDTH, HEIGHT);
}

function init() {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  sky.src = "http://html5.litten.com/images/slices/sky.png";
  city.src ="http://html5.litten.com/images/slices/city.png";
  ufo.src ="http://html5.litten.com/images/slices/ufo.png";  
  return setInterval(draw, 10);
}

function doKeyDown(evt){
  switch (evt.keyCode) {
    case 39:  /* Right arrow was pressed */
       if ((skyx + skydx) < (300 - skydx)){ 
        skyx += skydx; }
      else {
        skyx = 0;
      }
      if ((cityx + citydx) < (300 - citydx)){ 
        cityx += citydx; }
      else {
        cityx = 0;
      } 
       if (ufosprite < 64){ 
        ufosprite += 32; }
      else {
        ufosprite = 0 ;
      }       
  }
}

function draw() {
  clear();
  ctx.fillStyle = "black";
  rect(0,0,WIDTH,HEIGHT);
  ctx.drawImage(sky, skyx, 0, 300, 300, 0, 0, 300, 300);  
  ctx.drawImage(city, cityx, 0, 300, 300, 0, 0, 300, 300);  
  ctx.drawImage(ufo, ufosprite, 0, 32, 32, ufox, ufoy, 32, 32); 
}

init();
window.addEventListener('keydown',doKeyDown,true);
</script>
</section>


<h3><a name="thecode"></a>Here's the code</h3>
<pre><code>
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset="UTF-8" /&gt;
&lt;title&gt;Canvas Test&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;section&gt;

&lt;div&gt;
&lt;canvas id="canvas" width="300" height="300"&gt;
This text is displayed if your browser does not support HTML5 Canvas.
&lt;/canvas&gt;
&lt;/div&gt;

&lt;script type="text/javascript"&gt;
var canvas;             // Canvas object
var ctx;                // 2d Context object
var WIDTH = 300;        // Canvas width
var HEIGHT = 300;       // Canvas height
var sky = new Image();  // Sky image
var skydx = 2;          // Amount to move sky image
var skyx = 0;           // x coord to slice sky image
var city = new Image(); // City image
var citydx = 5;         // Amount to move city image
var cityx = 0;          // x coord to slice city image
var ufo = new Image();  // UFO image
var ufox = 150;         // x coord of UFO image
var ufoy = 250;         // y coord of UFO image
var ufosprite = 0;      // x coord to slice UFO image

function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
ctx.stroke();
}

function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}

function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
sky.src = "sky.png";
city.src ="city.png";
ufo.src ="ufo.png";
return setInterval(draw, 10);
}

function doKeyDown(evt){
switch (evt.keyCode) {
case 39:  /* Right arrow was pressed */
if ((skyx + skydx) &lt; (300 - skydx)){
skyx += skydx; }
else {
skyx = 0;
}
if ((cityx + citydx) &lt; (300 - citydx)){
cityx += citydx; }
else {
cityx = 0;
}
if (ufosprite &lt; 64){
ufosprite += 32; }
else {
ufosprite = 0 ;
}
}
}

function draw() {
clear();
ctx.fillStyle = "black";
rect(0,0,WIDTH,HEIGHT);
ctx.drawImage(sky, skyx, 0, 300, 300, 0, 0, 300, 300);
ctx.drawImage(city, cityx, 0, 300, 300, 0, 0, 300, 300);
ctx.drawImage(ufo, ufosprite, 0, 32, 32, ufox, ufoy, 32, 32);
}

init();
window.addEventListener('keydown',doKeyDown,true);
&lt;/script&gt;
&lt;/section&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre> 
<p>You can copy this code and paste it into a new file called something like slices.html and save it in the same directory with your 3 images for the sky, city and UFO (they must be in the same directory). When you open it with an HTML5 friendly browser like Firefox 3.6 it will display the canvas.</p>

<h3><a name="makeimage"></a>Making the images</h3>

<p>I spent maybe a half an hour making these images in Photoshop. They are very simple to illustrate the key concepts of this example. Given a few hours, an artist could really jazz these images up and make them look like a real video game.</p>

<p>The sky background<br/>
This image is two identical 300x300 images attached horizontally to make a single 600x300 image that we will move across the canvas by selecting 300X300 slices of it. Once we get to the end of the image (moving right) we reset the image back to the beginning which is the same because the leftmost 300x300 slice is identical to the rightmost 300x300 slice.</p>

<img src="http://html5.litten.com/wp-content/uploads/2010/07/sky2.png" alt="" title="sky2" width="200" height="100" class="alignnone size-full wp-image-522" />

<p>The city background<br/>
The city background is the same size as the sky background and is moved in the same manner of 300x300 slices. By putting it on top of the sky image and scrolling it slightly faster than the sky image we create the parallax scrolling effect.</p>

<img src="http://html5.litten.com/wp-content/uploads/2010/07/city2.png" alt="" title="city2" width="200" height="100" class="alignnone size-full wp-image-523" />

<p>Spaceship spritemap<br/>
The spritemap consists of three 32x32 images each a slightly modified version of the spaceship (different color lights). We display the spaceship one 32x32 slice at a time to create the magical illusion of animation.</p>

<img src="http://html5.litten.com/wp-content/uploads/2010/07/ufo2.png" alt="" title="ufo2" width="232" height="100" class="alignnone size-full wp-image-524" />

<h3><a name="moving"></a>Slicing and moving the images</h3>

<p>We have an event listener listening for keypresses on the keyboard.</p>
<pre><code>
window.addEventListener('keydown',doKeyDown,true);
</code></pre> 
<p>When a key is pressed it calls <code>doKeyDown()</code> and checks to see if the right arrow key was pressed. If it was it sets the variables for slicing our images.</p>
<pre><code>
function doKeyDown(evt){
  switch (evt.keyCode) {
    case 39:  /* Right arrow was pressed */
      if ((skyx + skydx) < (300 - skydx)){ 
        skyx += skydx; }
      else {
        skyx = 0;
      }
      if ((cityx + citydx) < (300 - citydx)){ 
        cityx += citydx; }
      else {
        cityx = 0;
      } 
      if (ufosprite < 64){ 
        ufosprite += 32; }
      else {
        ufosprite = 0 ;
      }       
  }
}
</code></pre> 
<p>First we check if our sky background slice is at the right end of the image and if it is, we set it back to <code>skyx = 0</code> which is the leftmost slice. If not then we increment it by skydx which is the amount that we move the sky for each keypress (must be lower than citydx to achieve the parallax effect).<br/>

Then we do the same for our city background.<br/>

Next we increment our slicing variable for the UFO to slice the next 32x32 sprite out of our UFO spritemap image.</p>

<p>Now that we have our variables set to new values, let's go to our <code>draw()</code> function (which runs every 10 milliseconds) and clear the canvas and redraw everything with our new values.</p>
<pre><code>
function draw() {
  clear();
  ctx.fillStyle = "black";
  rect(0,0,WIDTH,HEIGHT);
  ctx.drawImage(sky, skyx, 0, 300, 300, 0, 0, 300, 300);  
  ctx.drawImage(city, cityx, 0, 300, 300, 0, 0, 300, 300);  
  ctx.drawImage(ufo, ufosprite, 0, 32, 32, ufox, ufoy, 32, 32); 
}
</code></pre> 
<p>First we clear the canvas and paint it black so our white stars will show.</p>
<pre><code>
  clear();
  ctx.fillStyle = "black";
  rect(0,0,WIDTH,HEIGHT);
</code></pre> 
<p>Next we meet the wonderful <code>drawImage()</code> function. Here is the syntax and a picture from the W3C (<a href="http://dev.w3.org/html5/2dcontext/#images">http://dev.w3.org/html5/2dcontext/#images</a>). I can't say it any clearer.<p>
<blockquote>
<em>context . drawImage(image, dx, dy)<br/>
context . drawImage(image, dx, dy, dw, dh)<br/>
context . drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)<br/>
<br/>
    Draws the given image onto the canvas. The arguments are interpreted as follows: </em><br/>
<a href="http://dev.w3.org/html5/2dcontext/#images"><img src="http://html5.litten.com/wp-content/uploads/2010/07/drawImage.png" alt="" title="drawImage" width="356" height="356" class="alignnone size-full wp-image-529" /></a>  
</blockquote> 

<p> In the city and sky backgrounds the only variable that we change is the <code>sx</code> coordinate of where our slice begins. The slices are always 300x300 and are always drawn at (0,0) on our canvas.</p>
<pre><code>
  ctx.drawImage(sky, skyx, 0, 300, 300, 0, 0, 300, 300);  
  ctx.drawImage(city, cityx, 0, 300, 300, 0, 0, 300, 300);
</code></pre>   
<p>The spaceship also only changes the <code>sx</code> coordinate to slice the 32x32 sprite that we want to draw and is positioned on the canvas by ufox and ufoy which are always (150,250).</p>
<pre><code>
  ctx.drawImage(ufo, ufosprite, 0, 32, 32, ufox, ufoy, 32, 32); 
</code></pre>      
<h3><a name="fromhere"></a>Where to go from here</h3>
<p>You can now jazz up your canvas. Here are some suggestions.</p>

<p>Add movement in more directions.</p>

<p>Make better graphics.</p>

<p>Have the UFO shoot lasers or flames or peanut butter.</p>

<p>Have fun with the code as that is the easiest way to learn.</p>  

<p>If you have a question that you do not want published as a public comment, then use <a href="http://html5.litten.com/contact-me/">my contact page</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://html5.litten.com/slicing-spritemaps-and-parallax-scrolling-on-the-html5-canvas/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Graphing Data in the HTML5 Canvas Element Part III</title>
		<link>http://html5.litten.com/graphing-data-in-the-html5-canvas-element-part-iii/</link>
		<comments>http://html5.litten.com/graphing-data-in-the-html5-canvas-element-part-iii/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 14:22:12 +0000</pubDate>
		<dc:creator>James Litten</dc:creator>
				<category><![CDATA[Canvas Element]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[2d context]]></category>
		<category><![CDATA[graphing]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://html5.litten.com/?p=473</guid>
		<description><![CDATA[This is post 3 of a multipart series of posts. All of the code to try this example for yourself is included here but much of it is explained in the previous posts. The first and second parts can be found here. Graphing Data in the HTML5 Canvas Element Part I Graphing Data in the [...]]]></description>
			<content:encoded><![CDATA[<p>This is post 3 of a multipart series of posts. All of the code to try this example for yourself is included here but much of it is explained in the previous posts. The first and second parts can be found here.</p>
<p><a href="http://html5.litten.com/graphing-data-in-the-html5-canvas-element-part-i/">Graphing Data in the HTML5 Canvas Element Part I</a></p> 

<p><a href="http://html5.litten.com/graphing-data-in-the-html5-canvas-element-part-ii/">Graphing Data in the HTML5 Canvas Element Part II</a></p>

<p>In this post we will create bars on the graph by drawing rectangles whose size and position are based on the data that we are graphing. We will also increase the size of our graph area so our bars aren&#8217;t all scrunched together.</p>

This will allow us to go from this<br/><br/>
<img src="http://html5.litten.com/wp-content/uploads/2010/07/fig21.jpg" alt="" title="fig1"  class="alignnone size-full wp-image-191" border="0" /><br/>
<br/>
To this<br/><br/>
<img src="http://html5.litten.com/wp-content/uploads/2010/07/temps3.jpg" alt="" title="temps3" width="293" height="175" class="aligncenter size-full wp-image-481" />
<br/><span id="more-473"></span>
<p>This example is coded for readability and not for optimized operation. All you need is a text editor like notepad and an HTML5 friendly browser (I&#8217;m using Firefox 3.6).</p>
<pre><code>
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset="UTF-8" /&gt;
&lt;title&gt;Canvas Test&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;section&gt;
&lt;div&gt;
&lt;canvas id="canvas" width="310" height="165"&gt;
This text is displayed if your browser
does not support HTML5 Canvas.
&lt;/canvas&gt;
&lt;/div&gt;

&lt;script type="text/javascript"&gt;
var canvas;
var ctx;
var j;
var WIDTH = 310;
var HEIGHT = 165;
var temps = [80,95,85,78,92,95,79];
var graphWIDTH = 250;
var graphHEIGHT = 105;
var lingrad;
var padding = 30;

function drawaxes(){
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
/* y axis */
ctx.beginPath();
ctx.moveTo(padding,padding);
ctx.lineTo(padding,graphHEIGHT + padding);
ctx.stroke();
/* x axis */
ctx.moveTo(padding, graphHEIGHT + padding);
ctx.lineTo(graphWIDTH + padding,graphHEIGHT + padding);
ctx.stroke();
}

function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}

function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
lingrad = ctx.createLinearGradient(0,30,0,graphHEIGHT + 30);
lingrad.addColorStop(0, 'red');
lingrad.addColorStop(0.2, 'yellow');
lingrad.addColorStop(.5, 'green');
lingrad.addColorStop(.8, 'blue');
draw();
}

function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}

function plotdata(){
ctx.fillStyle = "black";
j = 0;
for (var i in temps){
rect(((j+1)*30) + padding,(graphHEIGHT + padding) -(temps[j]),10,
  (temps[j]));
j++;
}
}

function addlabels(){
ctx.font = "10pt Arial";
/* y axis labels */
ctx.fillText("Temps", 2, 15);
ctx.fillText("100", 5, 40);
ctx.fillText(" 80", 5, 60);
ctx.fillText(" 60", 5, 80);
ctx.fillText(" 40", 5, 100);
ctx.fillText(" 20", 5, 120);
/* x axis labels */
ctx.fillText("Days", 140, 160);
ctx.fillText("1", 61, 150);
ctx.fillText("2", 91, 150);
ctx.fillText("3", 121, 150);
ctx.fillText("4", 152, 150);
ctx.fillText("5", 182, 150);
ctx.fillText("6", 212, 150);
ctx.fillText("7", 242, 150);
}

function draw() {
clear();
ctx.globalAlpha = 0.4;
ctx.fillStyle = lingrad;
rect(padding,padding,graphWIDTH,graphHEIGHT);
ctx.globalAlpha = 1;
ctx.fillStyle = "black";
drawaxes();
addlabels();
plotdata();
}

init();
&lt;/script&gt;

&lt;/section&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<br/>

<p>You can copy this code and paste it into a new file called something like simplegraph3.html and when you open it with an HTML5 friendly browser like Firefox 3.6 it will display the graph.</p>

<p>Again our data will be 7 days of high temperatures.</p>
<table border="1">
<thead>
<tr><td align="center">Day</td>
<td align="center">Temperature</td></tr>
</thead>
<tbody>
<tr><td align="center">1</td>
<td align="center">80</td></tr>
<tr><td align="center">2</td>
<td align="center">95</td></tr>
<tr><td align="center">3</td>
<td align="center">75</td></tr>
<tr><td align="center">4</td>
<td align="center">78</td></tr>
<tr><td align="center">5</td>
<td align="center">92</td></tr>
<tr><td align="center">6</td>
<td align="center">95</td></tr>
<tr><td align="center">7</td>
<td align="center">79</td></tr>
</tbody>
</table>
<br/>
<p>We don&#8217;t need to change much in order to convert the line graph that we made in our last post to a bar graph.</p>
<p>First, since our bars are going to be 10 pixels wide we add 70 pixels (we are going to draw 7 bars) to our graphWIDTH variable and our canvas WIDTH variable. We also increase the width attribute of our &lt;canvas&gt; tag by 70.</p>

<pre><code>
var WIDTH = 310;
var graphWIDTH = 250;
&lt;canvas id="canvas" width="310" height="165"&gt;
</code></pre>
<p>Now we need to change our <code>plotdata()</code> function. Here is the new version for bars. </p>

<pre><code>
function plotdata(){
ctx.fillStyle = "black";
j = 0;
for (var i in temps){
rect(((j+1)*30) + padding,(graphHEIGHT + padding) -(temps[j]),10,
  (temps[j]));
j++;
}
}
</code></pre>
<p>We set the fillstyle of our bars to &#8216;black&#8217; and then we loop through our array of temperatures and use those values to create our rectangles.</p>

<pre><code>
rect(((j+1)*30) + padding,(graphHEIGHT + padding) -(temps[j]),10,
  (temps[j]));
</code></pre>
<p>We use <code>((j+1)*30) + padding</code> for our x coordinate. Adding one to j moves our first bar 30 pixels from the edge of the graph. The y coordinate is determined by the temperature data. The width is hard coded to 10 pixels and the height is determined by our temperature data.</p>

<p>It is very easy to load an array with data from pretty much any data source. As long as the graph is big enough, you can read and graph any one dimensional data set with this technique.</p>
]]></content:encoded>
			<wfw:commentRss>http://html5.litten.com/graphing-data-in-the-html5-canvas-element-part-iii/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>CSS 3.0 Series: The radial-gradient Object</title>
		<link>http://html5.litten.com/455/</link>
		<comments>http://html5.litten.com/455/#comments</comments>
		<pubDate>Wed, 14 Jul 2010 13:25:37 +0000</pubDate>
		<dc:creator>James Litten</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[CSS 3.0]]></category>
		<category><![CDATA[gradients]]></category>
		<category><![CDATA[radial gradient]]></category>

		<guid isPermaLink="false">http://html5.litten.com/?p=455</guid>
		<description><![CDATA[Radial gradiants are on the cutting edge of CSS . We&#8217;re going to be looking at some examples of their use and their current capabilities. In the previous post in this series we looked at linear gradients. The WebKit implementation of the radial gradient is just an extension of their linear gradient function while Mozilla [...]]]></description>
			<content:encoded><![CDATA[<p>Radial gradiants are on the cutting edge of CSS . We&#8217;re going to be looking at some examples of their use and their current capabilities.</p>
<p>In the previous post in this series we looked at <a href="http://html5.litten.com/css-3-0-series-the-linear-gradient-object/">linear gradients</a>. The WebKit implementation of the radial gradient is just an extension of their linear gradient function while Mozilla and W3C have opted to make the radial gradient have its own function.</p>

<p>Implementations and their Differences.</p>
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<pre>
W3C <a href="http://dev.w3.org/csswg/css3-images/#radial-gradients">syntax explanation here</a>  
radial-gradient([&lt;bg-position&gt; || &lt;angle&gt;,]?
 [&lt;shape&gt; || &lt;size&gt;,]? &lt;color-stop&gt;, &lt;color-stop&gt;
[, &lt;color-stop&gt;]*)

The W3C spec for the radial-gradient object is sufficiently
 complete for almost all tasks. It has the capability to create
 elliptical gradiants, and it is easy to define an angle,
 beginning and end of the line that defines the gradient.

Mozilla <a href="https://developer.mozilla.org/en/CSS/-moz-radial-gradient">syntax explanation here</a> 
-moz-radial-gradient( [&lt;position&gt; || &lt;angle&gt;,]?
 [&lt;shape&gt; || &lt;size&gt;,]? &lt;stop&gt;, &lt;stop&gt;
 [, &lt;stop&gt;]* )

The Mozilla implementation is fairly new so it is identical to
 the W3C spec. Firefox 3.6 and Minefield render all of the
 examples below very well.

WebKit <a href="http://developer.apple.com/safari/library/documentation/InternetWeb/Conceptual/SafariVisualEffectsProgGuide/Gradients/Gradients.html#//apple_ref/doc/uid/TP40008032-CH7-DontLinkElementID_2">syntax explanation here</a> 
-webkit-gradient(&lt;type&gt;, &lt;point&gt; [, &lt;radius&gt;]?,
 &lt;point&gt; [, &lt;radius&gt;]? [, &lt;stop&gt;]*)

Being pioneers and having early adoption of gradients,
 the WebKit implementation uses the same format for both
 linear and radial gradients. Unfortunately, this does not
 include the ability to do elliptical gradients. You specify
 a start circle and end circle in absolute pixel units, and
 then specify color stops at percentages between those
 two circles. 

Microsoft <a href="http://msdn.microsoft.com/en-us/library/ms532997%28VS.85,loband%29.aspx">syntax explanation here</a>
NONE
The Microsoft implementation of CSS gradients is limited to
 linear gradients that are either horizontal or vertical. No
 radial gradients. I've noticed that their linear gradient does
 not work in the IE9 platform preview (works in IE5 through IE8)
 so I wonder what they are up to.
</pre>
</div>
<br/>

<p><strong>IMPORTANT : Gradients can be used in any property that accepts images.</strong></p>
<br/>
<p><strong>Examples of radial gradiants applied to &lt;DIV&gt;﻿ tags.</strong></p>
<hr />


<p>Two colors #ffffff #F56991 from the center circular gradiant.</p>
<div  style=
"    width: 250px;
  height: 250px;
    padding: 15px;
    background: #F56991;
    color: #E8F3F8;
    border-radius:155px;     
    -moz-border-radius: 155px;    
    -webkit-border-radius: 155px;
    box-shadow: 10px 10px 25px #CCC;
    -moz-box-shadow: 5px 5px 25px #CCC;
    -webkit-box-shadow: 5px 5px 25px #CCC;
    background-position: center center;
    background-image: radial-gradient(center 45deg, circle closest-corner, #ffffff 0%, #F56991 100%);
    background-image: -moz-radial-gradient(center 45deg, circle closest-corner, #ffffff 0%, #F56991 100%);
    background-image: -webkit-gradient(radial, center center, 125, center center, 250, from(#ffffff), to(#F56991));
">&nbsp;</div>
<p>Here&#8217;s the code&#8230;</p>
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<pre>
&lt;div  style=
"    width: 250px;
height: 250px;
padding: 15px;
background: #F56991;
color: #E8F3F8;
border-radius:155px;
-moz-border-radius: 155px;
-webkit-border-radius: 155px;
box-shadow: 10px 10px 25px #CCC;
-moz-box-shadow: 5px 5px 25px #CCC;
-webkit-box-shadow: 5px 5px 25px #CCC;
background-position: center center;
background-image: radial-gradient(center
 45deg, circle closest-corner, #ffffff 0%, #F56991 100%);
background-image: -moz-radial-gradient(center
 45deg, circle closest-corner, #ffffff 0%, #F56991 100%);
background-image: -webkit-gradient(radial, center center,
 125, center center, 250, from(#ffffff), to(#F56991));
"&gt;&amp;nbsp;&lt;/div&gt;﻿
</pre>
</div>
<br/>
<hr />
<p>Two colors #ffffff #F56991 from (175,75) circular gradiant.</p>

<div  style=
"    width: 250px;
  height: 250px;
    padding: 15px;
    background: #F56991;
    color: #E8F3F8;
    border-radius:155px;     
    -moz-border-radius: 155px;    
    -webkit-border-radius: 155px;
    box-shadow: 10px 10px 25px #CCC;
    -moz-box-shadow: 5px 5px 25px #CCC;
    -webkit-box-shadow: 5px 5px 25px #CCC;
    background-position: center center;
    background-image: radial-gradient(175px 75px 45deg, circle , #ffffff 0%, #F56991 100%);
    background-image: -moz-radial-gradient(175px 75px 45deg, circle , #ffffff 0%, #F56991 100%);
    background-image: -webkit-gradient(radial, 175 75, 15, center center, 250, from(#ffffff), to(#F56991));
">&nbsp;</div>
<p>Here&#8217;s the code&#8230;</p>
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<pre>
&lt;div  style=
"    width: 250px;
height: 250px;
padding: 15px;
background: #F56991;
color: #E8F3F8;
border-radius:155px;
-moz-border-radius: 155px;
-webkit-border-radius: 155px;
box-shadow: 10px 10px 25px #CCC;
-moz-box-shadow: 5px 5px 25px #CCC;
-webkit-box-shadow: 5px 5px 25px #CCC;
background-position: center center;
background-image: radial-gradient(175px 75px
 45deg, circle , #ffffff 0%, #F56991 100%);
background-image: -moz-radial-gradient(175px 75px
 45deg, circle , #ffffff 0%, #F56991 100%);
background-image: -webkit-gradient(radial, 175 75, 15,
 center center, 250, from(#ffffff), to(#F56991));
"&gt;&amp;nbsp;&lt;/div&gt;
</pre>
</div>
<br/>
<hr />

<p>Three colors #ffffff #F56991 #8A2624 from (175,75) circular gradiant.</p>

<div  style=
"   width: 250px;
    height: 250px;
    padding: 15px;
    background: #F56991;
    color: #E8F3F8;
    border-radius:155px;     
    -moz-border-radius: 155px;    
    -webkit-border-radius: 155px;
    box-shadow: 10px 10px 25px #CCC;
    -moz-box-shadow: 5px 5px 25px #CCC;
    -webkit-box-shadow: 5px 5px 25px #CCC;
    background-position: center center;                                                     
    background-image: radial-gradient(175px 75px 45deg, circle , #ffffff 0%, #F56991 50%, #8A2624 100%);
    background-image: -moz-radial-gradient(175px 75px 45deg, circle , #ffffff 0%, #F56991 50%, #8A2624 100%);
    background-image: -webkit-gradient(radial, 175 75, 15, center center, 250, color-stop(0%, #ffffff), color-stop(50%, #F56991), color-stop(100%, #8A2624));
">&nbsp;</div>
<p>Here&#8217;s the code&#8230;</p>
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<pre>
&lt;div  style=
"   width: 250px;
height: 250px;
padding: 15px;
background: #F56991;
color: #E8F3F8;
border-radius:155px;
-moz-border-radius: 155px;
-webkit-border-radius: 155px;
box-shadow: 10px 10px 25px #CCC;
-moz-box-shadow: 5px 5px 25px #CCC;
-webkit-box-shadow: 5px 5px 25px #CCC;
background-position: center center;
background-image: radial-gradient(175px 75px
 45deg, circle , #ffffff 0%, #F56991 50%, #8A2624 100%);
background-image: -moz-radial-gradient(175px 75px
 45deg, circle , #ffffff 0%, #F56991 50%, #8A2624 100%);
background-image: -webkit-gradient(radial, 175 75, 15,
 center center, 250, color-stop(0%, #ffffff),
 color-stop(50%, #F56991), color-stop(100%, #8A2624));
"&gt;&amp;nbsp;&lt;/div&gt;
</pre>
</div>
<br/>
<hr />

<p>Three colors #ffffff #F56991 #8A2624 from (195,60) elliptical gradiant.</p>


<div  style=
"   width: 250px;
    height: 150px;
    padding: 15px;
    background: #F56991;
    color: #E8F3F8;
    border-radius: 155px / 100px;     
    -moz-border-radius: 155px / 100px;    
    -webkit-border-radius: 155px / 100px;
    box-shadow: 10px 10px 25px #CCC;
    -moz-box-shadow: 5px 5px 25px #CCC;
    -webkit-box-shadow: 5px 5px 25px #CCC;
    background-position: center center;                                                     
    background-image: radial-gradient(175px 75px 45deg, ellipse , #ffffff 0%, #F56991 50%, #8A2624 100%);
    background-image: -moz-radial-gradient(195px 60px 45deg, ellipse , #ffffff 0%, #F56991 50%, #8A2624 100%);
">&nbsp;</div>
<p>Here&#8217;s the code&#8230;</p>
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<pre>
&lt;div  style=
"   width: 250px;
height: 150px;
padding: 15px;
background: #F56991;
color: #E8F3F8;
border-radius: 155px / 100px;
-moz-border-radius: 155px / 100px;
-webkit-border-radius: 155px / 100px;
box-shadow: 10px 10px 25px #CCC;
-moz-box-shadow: 5px 5px 25px #CCC;
-webkit-box-shadow: 5px 5px 25px #CCC;
background-position: center center;
background-image: radial-gradient(175px 75px
 45deg, ellipse , #ffffff 0%, #F56991 50%, #8A2624 100%);
background-image: -moz-radial-gradient(195px 60px
 45deg, ellipse , #ffffff 0%, #F56991 50%, #8A2624 100%);
"&gt;&amp;nbsp;&lt;/div&gt;
</pre>
</div>
<br/>
<p>This only works for the Mozilla implementation</p>
<hr />

<p>Looking at these examples, there really isn&#8217;t much more to say than CSS radial gradients are not ready for primetime yet but they sure look nice.</p>
]]></content:encoded>
			<wfw:commentRss>http://html5.litten.com/455/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Make a Maze Game on an HTML5 Canvas</title>
		<link>http://html5.litten.com/make-a-maze-game-on-an-html5-canvas/</link>
		<comments>http://html5.litten.com/make-a-maze-game-on-an-html5-canvas/#comments</comments>
		<pubDate>Sun, 11 Jul 2010 17:26:16 +0000</pubDate>
		<dc:creator>James Litten</dc:creator>
				<category><![CDATA[Canvas Element]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[2d context]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://html5.litten.com/?p=422</guid>
		<description><![CDATA[One of the best ways to learn how to program in any language is to make a game and then change the code to create different variations on the game. I learned C++ long ago by creating an elevator simulation game (thanks Tom Swan). It&#8217;s fun and it is the closest you can come to [...]]]></description>
			<content:encoded><![CDATA[<p>One of the best ways to learn how to program in any language is to make a game and then change the code to create different variations on the game. I learned C++ long ago by creating an elevator simulation game (<a href="http://www.amazon.com/Learning-Book-Disk-Tom-Swan/dp/0672227851/ref=sr_1_28?ie=UTF8&#038;s=books&#038;qid=1278862682&#038;sr=1-28">thanks Tom Swan</a>). It&#8217;s fun and it is the closest you can come to &#8216;instant gratification&#8217; in programming.</p>
<p>Let&#8217;s make a maze game in an HTML5 canvas. In this post <a href="http://html5.litten.com/moving-shapes-on-the-html5-canvas-with-the-keyboard/">Moving Shapes on the HTML5 Canvas With the Keyboard</a> we learned to use keyboard input to move a shape around the canvas. All we need to do to make our game is</p>
<p>1. Add an image of the maze to the canvas.</p>
<p>2. Add collision detection code so we know if our shape hits a border in the maze.</p>
<br/>
<span id="more-422"></span>
<div style=" 
background-color: #F8F8F8;
padding: 10px;
width: 90%;
border-radius: 25px;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
    -webkit-box-shadow: 10px 10px 25px #D5D5D5;
    -moz-box-shadow: 10px 10px 25px #D5D5D5;
    box-shadow: 10px 10px 25px #D5D5D5;
">
<strong>Contents</strong>
<ul>
<li><a href="#whatyouneed">What you need to run this</a></li>
<li><a href="#thegame">Here&#8217;s the game (you need an HTML5 friendly browser to view this)</a></li>
<li><a href="#thecode">Here&#8217;s the code</a></li>
<li><a href="#mazeimage">Getting a maze image</a></li>
<li><a href="#addimage">Putting the maze image on your canvas</a></li>
<li><a href="#addcollision">Adding collision detection</a></li>
<li><a href="#fromhere">Where to go from here</a></li>
</ul>
</div>

<h3><a name="whatyouneed"></a>What you need to run this</h3>
<ul>
<li>An HTML5 friendly browser. I use <a href="http://www.google.com/chrome">Google Chrome</a>  and <a href="http://www.mozilla.com/en-US/firefox/personal.html">Firefox 3.6</a> .</li>
<li>A text editor like Notepad. I use <a href="http://www.pspad.com/en/">PSPad</a>  </li>
<li>A web server to upload your page to.</li>
<li>All the code for the maze game is in this post but it does build on the post <a href="http://html5.litten.com/moving-shapes-on-the-html5-canvas-with-the-keyboard/">Moving Shapes on the HTML5 Canvas With the Keyboard</a>  which you can refer to if you don&#8217;t understand the keyboard input routines.</li>
</ul>

<p>This example can not be run from your desktop because it uses the <code>getImageData()</code> method of the 2d context for collision detection. For security reasons it can only be run from a page served to the browser by a server. See the comments to <a href="http://aaronmt.com/?p=673">the post here</a> for more info .</p>

<h3><a name="thegame"></a>Here&#8217;s the game (you need an HTML5 friendly browser to view this)</h3>
<p>Here is our canvas in action. Since this post is longer than one page, pushing the arrow keys will scroll the page in addition to moving the square around. I substituted the arrow key keycodes with new keycodes.</p>
Press w to move up (keycode 87)<br/>
Press s to move down (keycode 83)<br/>
Press a to move left (keycode 65)<br/>
Press d to move right (keycode 68)<br/>

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    
  </head>
<body>
  <header> </header>
  <nav> </nav>
  <section>
    
    <div>
        <canvas id="canvas" width="482" height="482">
         This text is displayed if your browser does not support HTML5 Canvas.
        </canvas>
    </div>

<script type="text/javascript">
var canvas;  
var ctx;
var dx = 5;
var dy = 5;
var x = 200;
var y = 5;
var WIDTH = 482;
var HEIGHT = 482; 
var img = new Image();
var collision = 0;

function rect(x,y,w,h) {
  ctx.beginPath();
  ctx.rect(x,y,w,h);
  ctx.closePath();
  ctx.fill();
}
 
function clear() {
  ctx.clearRect(0, 0, WIDTH, HEIGHT);
  ctx.drawImage(img, 0, 0);
}

function init() {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  img.src = "http://html5.litten.com/images/maze.gif";
  return setInterval(draw, 10);
}

function doKeyDown(evt){
  switch (evt.keyCode) {
    case 87:  /* Up */
  		if (y - dy > 0){ 
        y -= dy;
        clear();
        checkcollision();
        if (collision == 1){
          y += dy;
          collision = 0;
        } 
      }

      break;
    case 83:  /* Down  */
  		if (y + dy < HEIGHT ){ 
        y += dy;
        clear();
        checkcollision();
        if (collision == 1){
          y -= dy;
          collision = 0;
        }
      }

      break;
    case 65:  /* Left  */
  		if (x - dx > 0){ 
        x -= dx;
        clear();
        checkcollision();
        if (collision == 1){
          x += dx;
          collision = 0;
        }
      }
      break;
    case 68:  /* Right  */
  		if ((x + dx < WIDTH)){ 
        x += dx;
        clear();
        checkcollision();
        if (collision == 1){
          x -= dx;
          collision = 0;
        }
      }
      break;
  }
}

function checkcollision() {
  var imgd = ctx.getImageData(x, y, 15, 15);
  var pix = imgd.data;
  for (var i = 0; n = pix.length, i < n; i += 4) {
  if (pix[i] == 0) {
      collision = 1;
    }
  }
}

function draw() {
  clear();          
  ctx.fillStyle = "purple";
  rect(x, y, 15,15);
}

init();
window.addEventListener('keydown',doKeyDown,true);
</script>
  </section>
  <aside> </aside>
  <footer> </footer>
</body>
</html>


<h3><a name="thecode"></a>Here's the code</h3>
<pre><code>
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset="UTF-8" /&gt;
&lt;title&gt;Canvas Maze Game&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;header&gt; &lt;/header&gt;
&lt;nav&gt; &lt;/nav&gt;
&lt;section&gt;

&lt;div&gt;
&lt;canvas id="canvas" width="482" height="482"&gt;
This text is displayed if your browser does not support HTML5 Canvas.
&lt;/canvas&gt;
&lt;/div&gt;

&lt;script type="text/javascript"&gt;
var canvas;
var ctx;
var dx = 5;
var dy = 5;
var x = 200;
var y = 5;
var WIDTH = 482;
var HEIGHT = 482;
var img = new Image();
var collision = 0;

function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}

function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
ctx.drawImage(img, 0, 0);
}

function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
img.src = "maze.gif";
return setInterval(draw, 10);
}

function doKeyDown(evt){
switch (evt.keyCode) {
case 38:  /* Up arrow was pressed */
if (y - dy &gt; 0){
y -= dy;
clear();
checkcollision();
if (collision == 1){
y += dy;
collision = 0;
}
}

break;
case 40:  /* Down arrow was pressed */
if (y + dy &lt; HEIGHT ){
y += dy;
clear();
checkcollision();
if (collision == 1){
y -= dy;
collision = 0;
}
}

break;
case 37:  /* Left arrow was pressed */
if (x - dx &gt; 0){
x -= dx;
clear();
checkcollision();
if (collision == 1){
x += dx;
collision = 0;
}
}
break;
case 39:  /* Right arrow was pressed */
if ((x + dx &lt; WIDTH)){
x += dx;
clear();
checkcollision();
if (collision == 1){
x -= dx;
collision = 0;
}
}
break;
}
}

function checkcollision() {
var imgd = ctx.getImageData(x, y, 15, 15);
var pix = imgd.data;
for (var i = 0; n = pix.length, i &lt; n; i += 4) {
if (pix[i] == 0) {
collision = 1;
}
}
}

function draw() {
clear();
ctx.fillStyle = "purple";
rect(x, y, 15,15);
}

init();
window.addEventListener('keydown',doKeyDown,true);
&lt;/script&gt;
&lt;/section&gt;
&lt;aside&gt; &lt;/aside&gt;
&lt;footer&gt; &lt;/footer&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>You can copy this code and paste it into a new file called something like maze.html and upload it to a webserver along with your maze image (they must be in the same directory). When you open it with an HTML5 friendly browser like Firefox 3.6 it will display the canvas with the maze game on it.</p>

<h3><a name="mazeimage"></a>Getting a maze image</h3>
<p>There is a free tool at <a href="http://hereandabove.com/maze/mazeorig.form.html">http://hereandabove.com/maze/mazeorig.form.html</a> that makes awesome maze images which you can right click and save in order to use them in your canvas page. Make sure that you set the Path width (in pixels) to be wider than your square plus whatever you use for dx and dy or else your square will always be colliding with a wall and won't go anywhere.</p>
Here is the image that I used. You can right click it and save it if you don't want to make your own right now.</p>
<img alt="" src="http://html5.litten.com/images/maze.gif" title="Maze" class="aligncenter" width="482" height="482" />

<h3><a name="addimage"></a>Putting the maze image on your canvas</h3>
<p>After getting a maze image, we need to add it to our canvas. Be sure that you upload the image into the same directory as your HTML file.</p>

<p>Make the canvas size the same size as the size of the image. My image is 482x482.</p> 
<pre><code>
&lt;div&gt;
&lt;canvas id="canvas" width="482" height="482"&gt;
This text is displayed if your browser does not support HTML5 Canvas.
&lt;/canvas&gt;
&lt;/div&gt;﻿
</code></pre>
<p>This makes it easier because the coordinate system of the canvas will match the coordinate system of the maze image.</p>

<p>Add a variable to hold our image.</p>
<pre><code>var img = new Image();</code></pre>

<p>We put our image into our new variable in our <code>init()</code> function which is the function that we call to start everything.</p>
<pre><code>
function init() {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  img.src = "maze.gif"; 
  return setInterval(draw, 10);
}
</code></pre>
<p>Then we draw our image onto the canvas in our <code>clear()</code> function.</p>
<pre><code>
function clear() {
  ctx.clearRect(0, 0, WIDTH, HEIGHT);
  ctx.drawImage(img, 0, 0);
}
</code></pre>
<p>This way when we call clear, only our little square is erased and we can look at the area of the maze where the square would go next and easily see if it is going to collide with a border.</p>
<p>The drawImage method of the 2d context has three arguments</p>
 <code> ctx.drawImage(variable holding the image, X coordinate of the top left of the image,  Y coordinate of the top left of the image)</code>
<p>When we call it, we put our maze image on the canvas with the top left corner at (0,0) which is the top left corner of our canvas also. Now when we look at a pixel like (100,100) on our canvas, we are also looking at pixel (100,100) on our image.</p>
  
  
<h3><a name="addcollision"></a>Adding collision detection</h3>
<p>Now all we need to do is check to make sure that we only move the square if the movement will not cause it to cross over one of the borders in the maze. Here's some pseudocode.</p>
<pre><code>
User presses an arrow key<br/>
Calculate where that would move the square to.<br/>
Look at all of the pixels on the maze image that the square will cover
in its new position (our square is 15x15 so we look at 225 pixels)<br/>
Are any of the pixels black (the maze is white with black borders. 
If a pixel is black that means the square would collide with a border)<br/>
YES: then do not move<br/>
NO: then move<br/>
</code></pre>
<br/>
<p>Our collision detection needs to occur when a user presses an arrow key to move the square.</p>
<p>Let's look at what happens when the up arrow is pressed.</p>
<pre><code>
function doKeyDown(evt){
  switch (evt.keyCode) {
    case 38:  /* Up arrow was pressed */
       if (y - dy > 0){ 
        y -= dy;
        clear();
        checkcollision();
        if (collision == 1){
          y += dy;
          collision = 0;
        } 
      }
</code></pre>      
<p>When a key is pressed on the keyboard, our event listener calls <code>doKeyDown()</code> which then checks to see if an arrow key was pressed. If the keyCode of the event is 38 then that means the up arrow key was pushed down.</p>
<p>First we check to make sure that the requested move won't move the square off of the canvas (y < 0).</p>
<pre><code>
  		if (y - dy > 0){ 
</code></pre>
<p>In order to move the square up we need to decrease the value of y by dy (dy and dx are set to the number of pixels that we move the square with each keypress. We are using dy = 5 and dx = 5 in our example).</p>
<pre><code>
        y -= dy;
</code></pre>        
<p>Now we need to check if the new y value causes our square to cross over a border in the maze.</p> 
<p>First we call our <code>clear()</code> function which redraws our canvas with the maze picture but does not draw our square.</p>
<pre><code>
function clear() {
  ctx.clearRect(0, 0, WIDTH, HEIGHT);
  ctx.drawImage(img, 0, 0);
}
</code></pre>
<p>This allows us to look at the pixels on the maze image where our square wants to move to. Now we can check if there is a collision between the square and any of the borders of the maze.</p>    
<p>Here's our <code>checkcollision()</code> function.</p>
<pre><code>
function checkcollision() {
  var imgd = ctx.getImageData(x, y, 15, 15);
  var pix = imgd.data;
  for (var i = 0; n = pix.length, i < n; i += 4) {
  if (pix[i] == 0) {
      collision = 1;
    }
  }
}
</code></pre>
<p>We get the image data from a square at (x, y, 15, 15) which is the 15x15 square area that our square will cover when we draw it. Then we load that data into a one dimensional array <code>pix[]</code>.</p>
<pre><code>
  var imgd = ctx.getImageData(x, y, 15, 15);
  var pix = imgd.data;
</code></pre>  
This array has four values for each pixel in our 15x15 area. The values are<br/>
RED value<br/>
GREEN value<br/>
BLUE value<br/>
ALPHA value<br/>
<br/>
A white pixel with no transparency looks like this<br/>
255<br/>
255<br/>
255<br/>
255<br/>
<br/>
A black pixel with no transparency looks like this<br/>              
0<br/>
0<br/>
0<br/>
255 <br/>
<br/>
<p>4 values X 15 pixels X 15 pixels = 900 values in our array but since we are looking for either black or white we can simply look at only the RED value of each pixel which means we compare 225 values instead of 900. If the pixel is black RED is 0 and if the pixel is white RED is 255 so we look at every fourth value in the array and check to see if it is 0 (for black). If it is, we set the variable <code>collision = 1</code>. </p>
<pre><code>
  for (var i = 0; n = pix.length, i < n; i += 4) {
  if (pix[i] == 0) {
      collision = 1;
    }
  }
</code></pre>  
<p>Now we are back in our keydown code for the up arrow where we check for the collision variable being set to 1 and if it is we undo the change to y and set the collision variable back to 0. Y remains unchanged and the next time the <code>draw()</code> function is called (it is called once every 10 milliseconds) it will not move the square up.</p>
<pre><code>
        if (collision == 1){
          y += dy;
          collision = 0;
</code></pre>      
<h3><a name="fromhere"></a>Where to go from here</h3>
<p>You can now jazz up your maze game. Here are some suggestions.</p>

<p>Add a timer display that counts down and the player must solve the maze before time runs out.</p>

<p>Use the timer to keep score so players can see who is the fastest.</p>

<p>Add sound effects. BEEP when the player hits a border or a fanfare when they win.</p>

<p>Add more mazes. Make ten mazes that are progressively more difficult and when the player finishes one, start the next one.</p>

<p>You can use any black and white image. Make a finger numbing spiral maze.</p>

<p>Make a trainer to help disabled people learn to use a <a href="http://www.amazon.com/OCZ-OCZMSNIA-NIA-Impulse-Actuator/dp/B00168VU4U/ref=sr_1_3?ie=UTF8&#038;s=electronics&#038;qid=1278868328&#038;sr=8-3">neural impulse actuator</a> to operate a computer.</p>

<p>Have fun with the code as that is the easiest way to learn.</p>

<p>If you have a question that you do not want published as a public comment, then use <a href="http://html5.litten.com/contact-me/">my contact page</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://html5.litten.com/make-a-maze-game-on-an-html5-canvas/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
