<?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>Script Tutorials &#187; JavaScript | Script Tutorials | Web development</title> <atom:link href="http://www.script-tutorials.com/category/javascript/feed/" rel="self" type="application/rss+xml" /><link>http://www.script-tutorials.com</link> <description>Tutorials for Web Developers</description> <lastBuildDate>Fri, 03 Feb 2012 06:07:51 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <item><title>Form Validation with Javascript and PHP</title><link>http://www.script-tutorials.com/form-validation-with-javascript-and-php/</link> <comments>http://www.script-tutorials.com/form-validation-with-javascript-and-php/#comments</comments> <pubDate>Wed, 01 Feb 2012 19:17:47 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[forms]]></category> <category><![CDATA[javascript]]></category> <category><![CDATA[validation]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1403</guid> <description><![CDATA[Form Validation with Javascript and PHP In this tutorial, I will show you how to create an attractive, pleasant to look form for your website and then I will explain you how to dynamically validate them using Javascript. We&#8217;ll also cover server-side validation with PHP to make everything 100% safe. This tutorial will help you [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/data-validation-html5/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/49.png" alt="Data Validation &#8211; How to Validate Forms using HTML5" /> Data Validation &#8211; How to Validate Forms using HTML5</a></li><li> <a
href="http://www.script-tutorials.com/animated-photo-gallery-grid-with-javascript/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/54/thumb.png" alt="Animated Photo Gallery (grid) with javascript" /> Animated Photo Gallery (grid) with javascript</a></li><li> <a
href="http://www.script-tutorials.com/cross-browser-effect-of-waves-using-javascript/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/81/thumb.png" alt="Creating Cross-browser Compatible Wave Effects Using Javascript" /> Creating Cross-browser Compatible Wave Effects Using Javascript</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Form Validation with Javascript and PHP" alt="Form Validation with Javascript and PHP" src="http://www.script-tutorials.com/demos/228/thumb.png"></div><p><strong>Form Validation with Javascript and PHP</strong><br
/> <br
/>In this tutorial, I will show you how to create an attractive, pleasant to look form for your website and then I will explain you how to dynamically validate them using Javascript. We&#8217;ll also cover server-side validation with PHP to make everything 100% safe. This tutorial will help you to add more functionality to your forms which leads to better user experience and better quality of your website. You may also enhance your already existing forms by adding them some fancy effects presented in this tutorial. Let&#8217;s get started! Info: If you&#8217;d like to modify already existing form by adding some javascript to it then skip HTML and CSS part of this tutorial and go to step five. Otherwise, if you&#8217;re planning to create new form start reading here.<br
/> <span
id="more-1403"></span></p><h3>Concept</h3><p>Let&#8217;s start with some brief explanation of what are we going to do. I&#8217;m sure that you&#8217;ve seen lots of different forms and I&#8217;m sure that filling in some of them was a lot more comfortable than filling in the other ones. I&#8217;m sure that this was caused in large part by some additional scripts. We&#8217;re going to cover a few field types including standard input field, password field, repeat password field, email field, options list and a few different scripts so I&#8217;m sure that you&#8217;ll find here something useful for you. Here are a few more things to consider while creating forms:</p><ul><li>Make sure that your form is as short as possible. People don&#8217;t like wasting time on filling in complex forms. They are likely to leave the page before they take any action. It&#8217;s better to ask for less important information after user is already registered (preferably only when you really need that information).</li><li>We want it to look neat and clean.</li><li>We want it to work seamlessly and without any strange behavior or errors.</li><li>We want to reduce number of fake submissions.</li></ul><h5 style="text-align: center;"><strong><a
title="Form Validation with Javascript and PHP - demo 228" href="http://www.script-tutorials.com/demos/228/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Form Validation with Javascript and PHP - package" href="http://www.script-tutorials.com/demos/228/source.zip" target="_blank">download in package</a></strong></h5><hr
/><h3>Project</h3><p>We&#8217;re going to start with HTML and then improve it with styles and scripts. At the end we&#8217;re going to I&#8217;m going to use the following fields in my form (numbers of allowed chars are in the brackets):</p><ul><li>Name (25)</li><li>Password (25)</li><li>Password Confirmation (25)</li><li>Email (50)</li><li>Gender (boolean)</li></ul><p>This is mine schedule. I found the best way to make each part of web is to start with HTML and then improve it by adding some style and scripts but you can actually start with preparing database (you can have your own DB table structure) or PHP script (step 12) and then take care of the rest pieces. Tip: You can increase maximum size of your text fields if you really need it but honestly I think values I chose are good enough.</p><h3>Step 1 &#8211; HTML Forms</h3><p>Lets prepare new folder &#8216;templates&#8217;, where we will put all our templates. Create a new document and name it main_page.html. Now we&#8217;re going to create HTML form and place it there. As you can see below there are some comments referring to each part of my code so I believe that at this point additional explanations are superfluous. I have also created a HTML table to align all the information. Here&#8217;s the code:</p><h4>templates/main_page.html</h4><pre class="brush:html">
&lt;form action=&quot;index.php&quot; method=&quot;post&quot; id=&quot;form&quot; onsubmit=&quot;return validate_all('results');&quot;&gt;
    &lt;table cellspacing=&quot;10&quot;&gt;
        &lt;tr&gt;&lt;td&gt;Login&lt;/td&gt;&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;login&quot; maxlength=&quot;25&quot; id=&quot;login&quot; onKeyUp=&quot;updatelength('login', 'login_length')&quot;&gt;&lt;br /&gt;&lt;div id=&quot;login_length&quot;&gt;&lt;/div&gt; &lt;/td&gt;&lt;/tr&gt;
        &lt;tr&gt;&lt;td&gt;Password&lt;/td&gt;&lt;td&gt;&lt;input type=&quot;password&quot; name=&quot;pass&quot; maxlength=&quot;25&quot; id=&quot;password&quot; onKeyUp=&quot;updatelength('password', 'pass_length')&quot;&gt;&lt;div id=&quot;pass_result&quot;&gt;&lt;/div&gt;&lt;br /&gt;&lt;div id=&quot;pass_length&quot;&gt;&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;
        &lt;tr&gt;&lt;td&gt;Confirm Password&lt;/td&gt;&lt;td&gt;&lt;input type=&quot;password&quot; name=&quot;cpass&quot; maxlength=&quot;25&quot; id=&quot;c_password&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
        &lt;tr&gt;&lt;td&gt;Gender&lt;/td&gt;&lt;td&gt;&lt;select name=&quot;gender&quot;&gt;&lt;option value=&quot;1&quot;&gt;male&lt;/option&gt;&lt;option value=&quot;0&quot;&gt;female&lt;/option&gt;&lt;/select&gt;&lt;/td&gt;&lt;/tr&gt;
        &lt;tr&gt;&lt;td&gt;Email&lt;/td&gt;&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;email&quot; maxlength=&quot;50&quot; id=&quot;email&quot; onKeyUp=&quot;updatelength('email', 'email_length')&quot;&gt;&lt;br /&gt;&lt;div id=&quot;email_length&quot;&gt;&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;
        &lt;tr&gt;&lt;td colspan=&quot;2&quot;&gt;&lt;input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Register&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
    &lt;/table&gt;
    &lt;h3 id=&quot;results&quot;&gt;&lt;/h3&gt;
&lt;/form&gt;
</pre><p>Things to note:</p><ul><li>Don&#8217;t forget to name your text fields, otherwise you won&#8217;t be able to receive data from them later on.</li><li>Maxlength parameter reduces number of characters you can use in each text field.</li><li>Action, method and id parameters are required so place them into form tag.</li><li>You can make table border visible by placing border=&#8221;1&#8243; in table tag if you want to actually see the table.</li></ul><p>Here&#8217;s the code of second page:</p><h4>templates/step2.html</h4><pre class="brush:html">
&lt;h2&gt;{errors}&lt;/h2&gt;
&lt;form action=&quot;index.php&quot; method=&quot;post&quot;&gt;
    &lt;table cellspacing=&quot;10&quot;&gt;
        &lt;input type=&quot;hidden&quot; name=&quot;login&quot; value=&quot;{login}&quot;&gt;
        &lt;input type=&quot;hidden&quot; name=&quot;pass&quot; value=&quot;{pass}&quot;&gt;
        &lt;input type=&quot;hidden&quot; name=&quot;cpass&quot; value=&quot;{cpass}&quot;&gt;
        &lt;input type=&quot;hidden&quot; name=&quot;gender&quot; value=&quot;{gender}&quot;&gt;
        &lt;input type=&quot;hidden&quot; name=&quot;email&quot; value=&quot;{email}&quot;&gt;
        &lt;tr&gt;&lt;td&gt;&lt;span&gt;Verification code&lt;/span&gt;&lt;/td&gt;&lt;td&gt;&lt;input name=&quot;vcode&quot;&gt;&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;
        &lt;tr&gt;&lt;td&gt;&lt;span&gt;Hint&lt;/span&gt;&lt;/td&gt;&lt;td&gt;&lt;i&gt;{vcode}&lt;/i&gt;&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;
        &lt;tr&gt;&lt;td colspan=&quot;2&quot;&gt;&lt;input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Register&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
    &lt;/table&gt;
&lt;/form&gt;
</pre><p>And &#8211; last one page:</p><h4>templates/step3.html</h4><pre class="brush:html">
&lt;h1&gt;Registration complete&lt;/h1&gt;
</pre><h3>Step 2 &#8211; Adding CSS</h3><p>Now we have our HTML form but it does not look attractively yet. As you may have guessed it is time to add some CSS and make our form look a little better. Here is my example of green form definitions:</p><h4>css/main.css</h4><pre class="brush:css">
form {
    background-color: #555;
    display: block;
    padding: 15px;
}
input[type=text], input[type=password], input[type=submit] {
    -moz-border-radius: 2px;
    -ms-border-radius: 2px;
    -o-border-radius: 2px;
    -webkit-border-radius: 2px;
    border-radius: 2px;
}
input[type=text], input[type=password], select {
    background-color: rgb(246, 254, 231);
    border-color: rgb(180, 207, 94);
    border-style: solid;
    border-width: 1px;
    font-size: 16px;
    height: 25px;
    margin-right: 10px;
    width: 200px;
}
input[type=submit]{
    cursor: pointer;
    font-size: 16px;
    height: 35px;
    padding: 5px;
}
input.wrong {
    border-color: rgb(180, 207, 94);
    background-color: rgb(255, 183, 183);
}
input.correct {
    border-color: rgb(180, 207, 94);
    background-color: rgb(220, 251, 164);
}
#pass_result {
    float: right;
}
</pre><p>Classes are named according to their further function. For example <b>.wrong</b> class will be used when text field contains wrong informations and so on. Also you should now add class parameter to each text field and elements that should have some style. To do it place <b>class=&#8221;class_name_here&#8221;</b> to <b>input</b> tags where <b>class_name_here</b> is name of class defined between <b>style</b> tags (see example if you are new to adding classes to elements). Add only <b>field</b> class to each text field, rest will be used later. I advise to modify styles a little by choosing different colors and values so that they could fulfill your requirements.</p><h3>Step 3 &#8211; Javascript</h3><p>This step will be about dynamic elements and how to use Javascript to create and then apply them wherever you would like to. After observing what some sites do I&#8217;ve noticed that there are plenty of such scripts (which I&#8217;m going to present here) recently, especially on big companies/corporations sites and popular services so I think this really make users happier and encourage them to fill forms in. Look around and check out some sign up forms (Google.com, Yahoo.com and flickr.com, ebay.com&#8230; yes, dynamic forms are almost everywhere now). Some easy to do scripts can reduce number of unnecessary clicks and let users create account (or whatever you are making form for) more quickly than before, not to mention they look much more prettily and cool. There are various places to put the javascript code as it was with CSS. It can either be written inside the <b>main_page.html</b> file using a tag or put to the other file and then include this file to <b>main_page.html</b>. Both case will use the same code to put scripts to your document. I chose second option so make separated script file (js/script.js) for our <b>main_page.html</b> file.</p><p>Each function from further steps should be placed where I made comment so between.</p><h3>Step 4 &#8211; Applying functions</h3><p>This is very important step so read it carefully. Adding javascript functions to your HTML form elements should be easy because it is very similar to adding CSS classes to them. Also to make it easier I tried to create functions from further steps alike to each other so that you can apply them almost the same way but for sure I will add some sample files each step to show you how it is made and I will write a little explanation to them. Generally if you want to add function (let&#8217;s say <b>updatelength()</b> from <b>Step 7 &#8211; Counter</b>) to <b>login</b> field you should replace:</p><pre class="brush:html">
    &lt;input type=&quot;text&quot; name=&quot;login&quot; maxlength=&quot;25&quot; id=&quot;login&quot;&gt;
</pre><p>with:</p><pre class="brush:html">
    &lt;input type=&quot;text&quot; name=&quot;login&quot; maxlength=&quot;25&quot; id=&quot;login&quot; onKeyUp=&quot;updatelength('login', 'login_length')&quot;&gt;&lt;br /&gt;&lt;div id=&quot;login_length&quot;&gt;&lt;/div&gt;
</pre><p>The only thing that has changed is <b>onKeyUp=&#8221;updatelength(&#8216;logid&#8217;, &#8216;login_length&#8217;)&#8221;</b> was added. Well, if we add something like this to our <b>input</b> we will observe what function is returning outcome in <b>div</b> tag with id &#8220;login_length&#8221;.</p><p><b>Why?</b></p><p>Because <b>updatelength()</b> function starts like this <b>&#8220;function updatelength(field, output){&#8230;&#8221;</b> (Step 7 &#8211; Counter) and that means it requires two arguments which are <b>ID OF TEXT FIELD IN HTML</b> and <b>ID OF DIV WHERE RESULT WILL BE</b>. Now it is easy, isn&#8217;t it? <img
src='http://www.script-tutorials.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> Rest of functions are similar to this one so I hope it won&#8217;t be a problem to apply it. Each one needs almost same values as arguments.<br
/> Notes:</p><ul><li>You can use more than one function to one text field by using a separator &#8220;;&#8221;. Example: <b>onKeyUp=&#8221;updatelength(&#8216;logid&#8217;, &#8216;login_length&#8217;); valid_length(&#8216;logid&#8217;, &#8216;login_o&#8217;);&#8221;</b></li><li>Look up to the source of example sites if you have any problems.</li></ul><h3>Step 5 &#8211; Counter</h3><p>So, here goes first script to improve our sign up form. It can be used in many other cases like adding a comment or posting message somewhere so you can attach it to more than one form. It will count characters we typed and tells us how many more we can write to the end of field. Short code and useful thing:</p><pre class="brush:js">
function updatelength(field, output){
    curr_length = document.getElementById(field).value.length;
    field_mlen = document.getElementById(field).maxLength;
    document.getElementById(output).innerHTML = curr_length+'/'+field_mlen;
    return 1;
}
</pre><p>Once you have placed it, you can run it using method presented in previous step (also there is example of usage described). This script checks how many characters did you use (each time you use one) and how many are allowed by text field&#8217;s <b>maxlength</b> parameter, then it changes value between the div tags. There are 2 variables called <b>&#8216;curr_length&#8217;</b> and <b>&#8216;field_mlen&#8217;</b>. First one gets and store number of characters you&#8217;ve typed (as I already wrote each time you type something in the field) and second one stores value of maxlength parameter of the field on which you are using this function. Then it simply shows both values with &#8216;/&#8217; separator in the middle. Note:</p><ul><li>I applied this script to every field</li></ul><h3>Step 6 &#8211; Password Strength</h3><p>Now it will be something which will check for how strong the password is. Scripts like this are usually not very extended so here is the basic version of it:</p><pre class="brush:js">
function check_v_pass(field, output) {
    pass_buf_value = document.getElementById(field).value;
    pass_level = 0;
    if (pass_buf_value.match(/[a-z]/g)) {
        pass_level++;
    }
    if (pass_buf_value.match(/[A-Z]/g)) {
        pass_level++;
    }
    if (pass_buf_value.match(/[0-9]/g)) {
        pass_level++;
    }
    if (pass_buf_value.length &lt; 5) {
        if(pass_level &gt;= 1) pass_level--;
    } else if (pass_buf_value.length &gt;= 20) {
        pass_level++;
    }
    output_val = '';
    switch (pass_level) {
        case 1: output_val='Weak'; break;
        case 2: output_val='Normal'; break;
        case 3: output_val='Strong'; break;
        case 4: output_val='Very strong'; break;
        default: output_val='Very weak'; break;
    }
    if (document.getElementById(output).value != pass_level) {
        document.getElementById(output).value = pass_level;
        document.getElementById(output).innerHTML = output_val;
    }
    return 1;
}
</pre><p>As a <b>&#8216;field&#8217;</b> argument we should put an ID of field to check and in <b>&#8216;output&#8217;</b> goes place where the result will be shown. Of course DON&#8217;T TYPE IT HERE but when you are using this function (here you are only creating it) so replace values only when you write <b>OnKeyUp=&quot;&#8230;</b> in your input <img
src='http://www.script-tutorials.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . Function also here contains two variables. First one called <b>&#8216;pass_level&#8217;</b> contains current password strength and it is set to 0 by default because password field is empty at the beginning. Second variable named <b>&#8216;pass_buf_value&#8217;</b> contains current value of your password field. Below those two you can see some if()-s, they are looking for some characters that may increase password strength level and if one of them find anything it updates value of <b>&#8216;pass_level&#8217;</b> variable by adding 1 to it. Of course rest of the script returns proper informations, it chooses right text depending on current <b>&#8216;pass_level&#8217;</b> value. Apply this script to your password field.</p><h3>Step 7 &#8211; Comparing passwords</h3><p>Third script compare value from password field with value from confirm password field to make user sure, he typed exactly what he wanted. Characters here are not visible so to check if user did not make any mistakes we need two different fields and both has to contain same values when typing, only then form is filled correctly:</p><pre class="brush:js">
function compare_valid(field, field2) {
    fld_val = document.getElementById(field).value;
    fld2_val = document.getElementById(field2).value;
    if (fld_val == fld2_val) {
        update_css_class(field2, 2);
        p_valid_r = 1;
    } else {
        update_css_class(field2, 1);
        p_valid_r = 0;
    }
    return p_valid_r;
}
</pre><p>Guess how to use it? Only tip I will give you is that you should use it only on the <b>compare password field</b> and nowhere else. Well, this script as you can see arrogates values of 2 fields to two different variables called <b>&#8216;fld_val&#8217;</b> and <b>&#8216;fld2_val&#8217;</b>. There is an if() construction below them which compares those two values and changes between 2 versions of style (green when everything is good and red when there are any errors).</p><h3>Step 8 &#8211; Email verification</h3><p>A bit more complicated script but usage is easy as always. Every email address must fulfill following criteria:<br
/> 1. Must have some characters at the beginning (letters or numbers (and some less important))<br
/> 2. Must have @ (at) character<br
/> 3. Must have domain name<br
/> a) Must have first word<br
/> b) Must have . (dot) character<br
/> c) Must have second word<br
/> 4. And in the event that somebody believe his email address contains big letters it must convert characters to small ones</p><pre class="brush:js">
function check_v_mail(field) {
    fld_value = document.getElementById(field).value;
    is_m_valid = 0;
    if (fld_value.indexOf('@') &gt;= 1) {
        m_valid_dom = fld_value.substr(fld_value.indexOf('@')+1);
        if (m_valid_dom.indexOf('@') == -1) {
            if (m_valid_dom.indexOf('.') &gt;= 1) {
                m_valid_dom_e = m_valid_dom.substr(m_valid_dom.indexOf('.')+1);
                if (m_valid_dom_e.length &gt;= 1) {
                    is_m_valid = 1;
                }
            }
        }
    }
    if (is_m_valid) {
        update_css_class(field, 2);
        m_valid_r = 1;
    } else {
        update_css_class(field, 1);
        m_valid_r = 0;
    }
    return m_valid_r;
}
</pre><p>Place <b>OnKeyUp=&quot;&#8230;</b> into <b>input</b> tag where email address is and create new <b>div</b> with adequate ID to make it work. This function basically looks up if the email address is typed correctly. First it arrogates value of the field to <b>&#8216;fld_value&#8217;</b> variable to work with it. Everything is supervised by 4 if() constructions. They are step by step checking if there is @ symbol (1), then if it is on the second or further position (2). At the end if there is &quot;dot&quot; character after @ symbol (3) and finally if there are any characters before and after this &quot;dot&quot; (4). If any of if()-a find error it stops script and switches to red style wrong style of field. Those if()-s are a bit complicated as you can see but finally result is same as always, it chooses between green and red style and then shows it. Second part of this script is similar to switching between two options in already explained part so it should be clear for now.</p><h3>Step 9 &#8211; Empty fields</h3><p>Short function checking if there is more than 0 characters in our inputs. If there are empty spaces somewhere we can&#8217;t create new account:</p><pre class="brush:js">
function valid_length(field) {
    length_df = document.getElementById(field).value.length;
    if (length_df &gt;= 1 &amp;&amp; length_df &lt;= document.getElementById(field).maxLength) {
        update_css_class(field, 2);
        ret_len = 1;
    } else {
        update_css_class(field, 1);
        ret_len = 0;
    }
    return ret_len;
}
</pre><p>Like usually here also we have to give a text field ID and ID of div where result of script should be as an arguments. Add this script to each field (except gender one). This one has only one interesting part to explain because rest should be clear for you already. I&#8217;m talking about this long if() construction in the third line. It first checks if value of the field has at least one character and than in its second part if it has no more than &#8216;max number&#8217; of characters. Then it just changes between two options &#8211; right and wrong.</p><h3>Step 10 &#8211; Coloring</h3><p>This one is very short and only changes mode between two classes to make better visual effects. Classes must be defined in our CSS part of document (they are if you copied definitions from step 4). I called them <b>wrong</b> and <b>correct</b>:</p><pre class="brush:js">
function update_css_class(field, class_index) {
    if (class_index == 1) {
        class_s = 'wrong';
    } else if (class_index == 2) {
        class_s = 'correct';
    }
    document.getElementById(field).className = class_s;
    return 1;
}
</pre><p>As you may have already noticed this function is ran by other ones. Previous and further scripts puts arguments here. First argument is an ID of field you are currently working with and second is number 1 or 2. This numbers are being changed depending on actual field status to let then change its style to correct one. Let&#8217;s continue to next step.</p><h3>Step 11 &#8211; Last Javascript verification</h3><p>This is the last script using javascript. It calls out every function once more for sure and returns encountered errors or allows us to continue. It does not require refreshing whole page but check form quickly after pressing &quot;Register&quot;. That&#8217;s very important script and other ones were mostly make to let this one work:</p><pre class="brush:js">
function validate_all(output) {
    t1 = valid_length('login');
    t2 = valid_length('password');
    t3 = compare_valid('password', 'c_password');
    t4 = check_v_mail('email');
    t5 = check_v_pass('password', 'pass_result');

    errorlist = '';
    if (! t1) {
        errorlist += 'Login is too short/long&lt;br /&gt;';
    }
    if (! t2) {
        errorlist += 'Password is too short/long&lt;br /&gt;';
    }
    if (! t3) {
        errorlist += 'Passwords are not the same&lt;br /&gt;';
    }
    if (! t4) {
        errorlist += 'Mail is wrong&lt;br /&gt;';
    }
    if (errorlist) {
        document.getElementById(output).innerHTML = errorlist;
        return false;
    }
    return true;
}
</pre><p>This script to work must be added to your submission form. And don&#8217;t forget to put <b>div</b> tag with &#8216;results&#8217; id somewhere so that there outcome could go (in my case it is at the bottom of form so below just made &#8216;button&#8217;). Once you press new button this function recalls other functions from previous steps and checks once more for any mistakes for sure. If everything is fine it let you create account but if something is wrong it shows errors there where you&#8217;ve placed your <b>&#8216;div&#8217;</b> with <b>&#8216;results&#8217;</b> ID. Also in this script you can define your own error messages.</p><h3>Step 12 &#8211; Final verification</h3><p>From now it will be mostly about PHP (and MySQL) so if you don&#8217;t want to make such a form on you website you can just leave it and use methods I showed in other situations <img
src='http://www.script-tutorials.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> Otherwise if you would like to store account data using MySQL database continue reading.<br
/> Javascript actually doesn&#8217;t protect our database from anything, it only makes people lifes easier <img
src='http://www.script-tutorials.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> If we want to be sure that filled form is 100% correct we must use PHP verification before we can add anything to our database &#8211; that is because if somebody will turn javascript off still he can write whatever he want while creating account and this may make database errors occurs. To add some very simply PHP script create index.php file which will be launched after pressing &quot;Register&quot; button. Well, here&#8217;s the code you should put to your index.php file:</p><h4>index.php</h4><pre class="brush:php">
&lt;?php

// set error reporting level
if (version_compare(phpversion(), '5.3.0', '&gt;=') == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE);

session_start();
if (isset($_POST['submit'])) {

    $sLogin = escape($_POST['login']);
    $sPass = escape($_POST['pass']);
    $sCPass = escape($_POST['cpass']);
    $sEmail = escape($_POST['email']);
    $iGender = (int)$_POST['gender'];

    $sErrors = '';
    if (strlen($sLogin) &gt;= 1 and strlen($sLogin) &lt;= 25) {
        if (strlen($sPass) &gt;= 1 and strlen($sPass) &lt;= 25) {
            if (strlen($sEmail) &gt;= 1 and strlen($sEmail) &lt;= 55) {
                if ($sPass == $sCPass) {
                    if (ereg('^[a-zA-Z0-9\-\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$', $sEmail)) {
                        if ($iGender == '1' xor $iGender == '0') {
                            $sVcode = escape($_POST['vcode']);
                            if (! isset($_SESSION['valdiation_code'])) {
                                // Here you can send him some verification code (by email or any another ways)
                                $sCode = uniqid(rand(), true);
                                $_SESSION['valdiation_code'] = md5($sCode);

                            } elseif (md5($sVcode) == $_SESSION['valdiation_code']) {
                                // Here you can add him to database
                                // mysql_query('INSERT INTO ....

                                // display step 3 (final step)
                                echo strtr(file_get_contents('templates/step3.html'), array());
                                exit;
                            } else {
                                $sErrors = 'Verification code is wrong';
                            }
                        } else {
                            $sErrors = 'Gender is wrong';
                        }
                    } else {
                        $sErrors = 'Email is wrong';
                    }
                } else {
                    $sErrors = 'Passwords are not the same';
                }
            } else {
                $sErrors = 'Address email is too long';
            }
        } else {
            $sErrors = 'Password is too long';
        }
    } else {
        $sErrors = 'Login is too long';
    }

    // display step 2
    $aParams = array(
        '{errors}' =&gt; $sErrors,
        '{login}' =&gt; $sLogin,
        '{pass}' =&gt; $sPass,
        '{cpass}' =&gt; $sCPass,
        '{gender}' =&gt; $iGender,
        '{email}' =&gt; $sEmail,
        '{vcode}' =&gt; $sCode
    );
    echo strtr(file_get_contents('templates/step2.html'), $aParams);
    exit;
}

// unset validation code if exists
unset($_SESSION['valdiation_code']);

// draw registration page
echo strtr(file_get_contents('templates/main_page.html'), array());

// extra useful function to make POST variables more safe
function escape($s) {
    //return mysql_real_escape_string(strip_tags($s)); // uncomment in when you will use connection with database
    return strip_tags($s);
}
</pre><p>Now, lets try to understand this. This script generally does EXACTLY the same what previous JS scripts did but it is launched on the server side to check everything once more. Continue reading to check how does it work.</p><p>So, please pay attention to all our checks, and &#8211; to added validation functional. When our form submitted, the next step will contain single field to accept some validation code. Of course, for our demo page you always can see that checking code. But, as some suggestion &#8211; I can offer you to enable email confirmation (as example). So, you have to add email sending to this code also. And, only after accepting that extra validation code (if this code was right) &#8211; only then allow member registration. Please read my comments carefully.</p><hr
/><h5 style="text-align: center;"><strong><a
title="Form Validation with Javascript and PHP - demo 228" href="http://www.script-tutorials.com/demos/228/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Form Validation with Javascript and PHP - package" href="http://www.script-tutorials.com/demos/228/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>So that is all for now. In the final version I also added some classes which make table better positioned (stable) so make sure you&#8217;ve checked it out. While creating your own form you can expand it anyhow relying on what I wrote or try to use your imagination to create something better. Hope you enjoyed it. Good luck and welcome back!</p><div
class="shr-publisher-1403"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/data-validation-html5/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/49.png" alt="Data Validation &#8211; How to Validate Forms using HTML5" /> <br
/> Data Validation &#8211; How to Validate Forms using HTML5</a></li><li> <a
href="http://www.script-tutorials.com/animated-photo-gallery-grid-with-javascript/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/54/thumb.png" alt="Animated Photo Gallery (grid) with javascript" /> <br
/> Animated Photo Gallery (grid) with javascript</a></li><li> <a
href="http://www.script-tutorials.com/cross-browser-effect-of-waves-using-javascript/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/81/thumb.png" alt="Creating Cross-browser Compatible Wave Effects Using Javascript" /> <br
/> Creating Cross-browser Compatible Wave Effects Using Javascript</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/form-validation-with-javascript-and-php/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Fullscreen Javascript Slide navigation</title><link>http://www.script-tutorials.com/fullscreen-javascript-slide-navigation/</link> <comments>http://www.script-tutorials.com/fullscreen-javascript-slide-navigation/#comments</comments> <pubDate>Tue, 10 Jan 2012 14:43:02 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[JavaScript]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1350</guid> <description><![CDATA[Fullscreen Javascript Slide navigation Today &#8211; new pure javascript tutorial-demonstration. Result page will contain 16 slides (pages). Four in each row, four columns, plus we will add animated navigation to them through css3 arrows (at sides of screen). Plus, we will have mini-navigation bar for better navigation. Live Demo download in package Ok, download the [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/css3-bottom-navigation-menu/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/170/thumb.png" alt="Creating a Toggle CSS3 Bottom Navigation Bar" /> Creating a Toggle CSS3 Bottom Navigation Bar</a></li><li> <a
href="http://www.script-tutorials.com/css3-onclick-vertical-metal-menu/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/162/thumb.png" alt="Creating an Accordian like CSS3 Onclick Vertical Navigation" /> Creating an Accordian like CSS3 Onclick Vertical Navigation</a></li><li> <a
href="http://www.script-tutorials.com/css3-metal-menu-with-icons/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/152/thumb.png" alt="Creating a Multilevel CSS3 Metal Navigation with icons" /> Creating a Multilevel CSS3 Metal Navigation with icons</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Fullscreen Javascript Slide navigation" alt="Fullscreen Javascript Slide navigation" src="http://www.script-tutorials.com/demos/215/thumb.png" /></div><p><strong>Fullscreen Javascript Slide navigation</strong></p><p>Today &#8211; new pure javascript tutorial-demonstration. Result page will contain 16 slides (pages). Four in each row, four columns, plus we will add animated navigation to them through css3 arrows (at sides of screen). Plus, we will have mini-navigation bar for better navigation.</p><p><span
id="more-1350"></span></p><hr
/><h5 style="text-align: center;"><strong><a
title="Fullscreen Javascript Slide navigation - demo 215" href="http://www.script-tutorials.com/demos/215/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Fullscreen Javascript Slide navigation - package" href="http://www.script-tutorials.com/demos/215/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Ok, download the example files and lets start coding !</p><hr
/><h3>Step 1. HTML markup</h3><p>In our markup you can see 16 &#8216;pages&#8217; and mini-navigation for our slides. Here it is.</p><h4>index.html</h4><pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;Fullscreen Javascript Slide navigation | Script Tutorials&lt;/title&gt;
        &lt;link href=&quot;css/layout.css&quot; type=&quot;text/css&quot; rel=&quot;stylesheet&quot;&gt;
        &lt;script src=&quot;js/main.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class=&quot;container&quot; id=&quot;container&quot;&gt;
            &lt;div id=&quot;pages&quot;&gt;
                &lt;div id=&quot;page1&quot;&gt;
                    &lt;a href=&quot;#page2&quot; class=&quot;go right&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page5&quot; class=&quot;go bottom&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page2&quot;&gt;
                    &lt;a href=&quot;#page1&quot; class=&quot;go left&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page3&quot; class=&quot;go right&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page6&quot; class=&quot;go bottom&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page3&quot;&gt;
                    &lt;a href=&quot;#page2&quot; class=&quot;go left&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page4&quot; class=&quot;go right&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page7&quot; class=&quot;go bottom&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page4&quot;&gt;
                    &lt;a href=&quot;#page3&quot; class=&quot;go left&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page8&quot; class=&quot;go bottom&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page5&quot;&gt;
                    &lt;a href=&quot;#page1&quot; class=&quot;go top&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page6&quot; class=&quot;go right&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page9&quot; class=&quot;go bottom&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page6&quot;&gt;
                    &lt;a href=&quot;#page5&quot; class=&quot;go left&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page2&quot; class=&quot;go top&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page7&quot; class=&quot;go right&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page10&quot; class=&quot;go bottom&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page7&quot;&gt;
                    &lt;a href=&quot;#page6&quot; class=&quot;go left&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page3&quot; class=&quot;go top&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page8&quot; class=&quot;go right&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page11&quot; class=&quot;go bottom&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page8&quot;&gt;
                    &lt;a href=&quot;#page7&quot; class=&quot;go left&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page4&quot; class=&quot;go top&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page12&quot; class=&quot;go bottom&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page9&quot;&gt;
                    &lt;a href=&quot;#page5&quot; class=&quot;go top&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page10&quot; class=&quot;go right&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page13&quot; class=&quot;go bottom&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page10&quot;&gt;
                    &lt;a href=&quot;#page9&quot; class=&quot;go left&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page6&quot; class=&quot;go top&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page11&quot; class=&quot;go right&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page14&quot; class=&quot;go bottom&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page11&quot;&gt;
                    &lt;a href=&quot;#page10&quot; class=&quot;go left&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page7&quot; class=&quot;go top&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page12&quot; class=&quot;go right&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page15&quot; class=&quot;go bottom&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page12&quot;&gt;
                    &lt;a href=&quot;#page11&quot; class=&quot;go left&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page8&quot; class=&quot;go top&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page16&quot; class=&quot;go bottom&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page13&quot;&gt;
                    &lt;a href=&quot;#page9&quot; class=&quot;go top&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page14&quot; class=&quot;go right&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page14&quot;&gt;
                    &lt;a href=&quot;#page13&quot; class=&quot;go left&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page10&quot; class=&quot;go top&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page15&quot; class=&quot;go right&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page15&quot;&gt;
                    &lt;a href=&quot;#page14&quot; class=&quot;go left&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page11&quot; class=&quot;go top&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page16&quot; class=&quot;go right&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div id=&quot;page16&quot;&gt;
                    &lt;a href=&quot;#page15&quot; class=&quot;go left&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page12&quot; class=&quot;go top&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
            &lt;/div&gt;
            &lt;div id=&quot;nav&quot;&gt;
                &lt;div&gt;Fullscreen Javascript Slide navigation&lt;/div&gt;
                &lt;div style=&quot;width:130px&quot;&gt;
                    &lt;a href=&quot;#page1&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page2&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page3&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page4&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page5&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page6&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page7&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page8&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page9&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page10&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page11&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page12&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page13&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page14&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page15&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                    &lt;a href=&quot;#page16&quot; class=&quot;go&quot;&gt;&lt;/a&gt;
                &lt;/div&gt;
                &lt;div&gt;&lt;a href=&quot;http://www.script-tutorials.com/fullscreen-javascript-slide-navigation/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;&lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><h3>Step 2. CSS</h3><p>Now &#8211; stylesheets for our slides:</p><h4>css/layout.css</h4><pre class="brush:css">
*{
    margin:0;
    padding:0;
}
body {
    background-color:#aaa;
    color:#fff;
    font:16px Arial,sans-serif;
    font-weight:700;
    margin:0px;
    padding:0px;
    background:#111;
    width:100%;
    height:100%;
}
a.stuts,a.stuts:visited{
    color: #FCFCFC;
    font-size: 14px;
    text-decoration: none;
}
.stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}
.container {
    position: absolute;
    left: 0;
    top: 0;
    background: #000;
    overflow: hidden;
    width: 100%;
    height: 100%;
}
#pages {
    left:0;
    position:absolute;
    top:0;
}
#nav {
    background-color:rgba(0, 0, 0, 0.8);
    margin:0;
    outline:#333 solid 1px;
    padding:10px;
    position:fixed;
    right:200px;
    top:50px;
    width:200px;
}
#nav div a.go {
    background:#333;
    float:left;
    height:25px;
    margin:3px;
    overflow:hidden;
    text-decoration:none;
    width:25px;
}
#nav div a.go:visited,#nav div a.visited {
    background-color:#666;
}
#nav div a.go:active,#nav div a.active {
    background-color:#fff !important;
}
#nav div a.go:hover,#nav div a.go:focus {
    background-color:#00f;
}
#pages &gt; div {
    height:1100px;
    position:absolute;
    width:1700px;
}
#page1 {
    background:url(../images/1.jpg) no-repeat center center;
    left:0;
    top:0;
}
#page2 {
    background:url(../images/2.jpg) no-repeat center center;
    left:1800px;
    top:0;
}
#page3 {
    background:url(../images/3.jpg) no-repeat center center;
    left:3600px;
    top:0;
}
#page4 {
    background:url(../images/4.jpg) no-repeat center center;
    left:5400px;
    top:0;
}
#page5 {
    background:url(../images/5.jpg) no-repeat center center;
    left:0;
    top:1300px;
}
#page6 {
    background:url(../images/6.jpg) no-repeat center center;
    left:1800px;
    top:1300px;
}
#page7 {
    background:url(../images/7.jpg) no-repeat left center;
    left:3600px;
    top:1300px;
}
#page8 {
    background:url(../images/8.jpg) no-repeat center center;
    left:5400px;
    top:1300px;
}
#page9 {
    background:url(../images/9.jpg) no-repeat center center;
    left:0;
    top:2600px;
}
#page10 {
    background:url(../images/10.jpg) no-repeat center center;
    left:1800px;
    top:2600px;
}
#page11 {
    background:url(../images/11.jpg) no-repeat center center;
    left:3600px;
    top:2600px;
}
#page12 {
    background:url(../images/12.jpg) no-repeat center center;
    left:5400px;
    top:2600px;
}
#page13 {
    background:url(../images/13.jpg) no-repeat center center;
    left:0;
    top:3900px;
}
#page14 {
    background:url(../images/14.jpg) no-repeat center center;
    left:1800px;
    top:3900px;
}
#page15 {
    background:url(../images/15.jpg) no-repeat center center;
    left:3600px;
    top:3900px;
}
#page16 {
    background:url(../images/16.jpg) no-repeat center center;
    left:5400px;
    top:3900px;
}
#pages .left {
    border-bottom:transparent solid 50px;
    border-right:#FFF solid 80px;
    border-top:transparent solid 50px;
    height:0;
    left:20px;
    position:absolute;
    top:50%;
    width:0;
}
#pages .right {
    border-bottom:transparent solid 50px;
    border-left:#FFF solid 80px;
    border-top:transparent solid 50px;
    height:0;
    position:absolute;
    right:20px;
    top:50%;
    width:0;
}
#pages .top {
    border-bottom:#FFF solid 80px;
    border-left:transparent solid 50px;
    border-right:transparent solid 50px;
    height:0;
    left:50%;
    position:absolute;
    top:20px;
    width:0;
}
#pages .bottom {
    border-left:transparent solid 50px;
    border-right:transparent solid 50px;
    border-top:#FFF solid 80px;
    bottom:20px;
    height:0;
    left:50%;
    position:absolute;
    width:0;
}
#pages .left:hover {
    border-right:red solid 80px;
}
#pages .right:hover {
    border-left:red solid 80px;
}
#pages .top:hover {
    border-bottom:red solid 80px;
}
#pages .bottom:hover {
    border-top:red solid 80px;
}
#nav &gt; div {
    margin:10px auto;
    overflow:hidden;
    text-align:center;
}
</pre><h3>Step 3. JS</h3><p>ANd now &#8211; our javascript code:</p><h4>js/main.js</h4><pre class="brush:js">
var navi = {
    // variables
    aPages : [],
    aLinks : [],
    tween : {},
    oParent : null,
    oPages : null,
    bRunning : null,
    sTargPage : null,
    sCurPage : null,
    bHash : null,
    sOldH : null,
    bUpdateH : true,

    // initialization
    init : function (aParams) {
        this.oPages = document.getElementById(aParams.pages_id);
        this.oParent  = document.getElementById(aParams.parent_id);

        var aAEls = this.oParent.getElementsByTagName('a');
        var i = 0; var p = null;
        while (p = aAEls[i++]) {
            if (p.className &amp;&amp; p.className.indexOf('go') &gt;= 0) {
                var sHref = p.href.split('#')[1];
                var oDst = document.getElementById(sHref);
                if (oDst) {
                    // fill-in pages array
                    this.aPages[sHref] = {
                        oObj:  oDst,
                        iXPos: -oDst.offsetLeft,
                        iYPos: -oDst.offsetTop
                    };

                    // fill-in links array
                    this.aLinks.push({a: p, oObj: oDst});

                    p.onclick = function () {
                        navi.goto(this.href.split('#')[1], aParams.duration);
                        return false;
                    }
                }
            }
        }

        this.resize();

        if ('onhashchange' in window) {
            if (location.hash !== '' &amp;&amp; location.hash !== '#') {
                this.sOldH = location.hash.substring(1);
                this.goto(this.sOldH, -1);
            } else
                this.goto('page1', -1);
            this.bHash = true;

            window.onhashchange = function() {
                if (location.hash.substring(1) !== navi.sOldH) {
                    navi.sOldH = location.hash.substring(1);
                    if (navi.sOldH == '') {
                        navi.bUpdateH = false;
                    }
                    navi.goto(navi.sOldH, aParams.duration);
                }
                return false;
            }
        }
    },

    // on resize
    resize : function () {
        var iCurW = this.oParent.offsetWidth; // current sizes
        var iCurH = this.oParent.offsetHeight;
        for (var i in this.aPages) { // for each page
            var oPage = this.aPages[i];
            var iNewX = Math.round(oPage.oObj.offsetLeft * iCurW / oPage.oObj.offsetWidth); // new sizes
            var iNewY = Math.round(oPage.oObj.offsetTop  * iCurH / oPage.oObj.offsetHeight);
            oPage.oObj.style.left   = iNewX + 'px';
            oPage.oObj.style.top    = iNewY + 'px';
            oPage.oObj.style.width  = iCurW + 'px';
            oPage.oObj.style.height = iCurH + 'px';
            oPage.iXPos = -iNewX;
            oPage.iYPos = -iNewY;

            if (this.sCurPage)
                this.goto(this.sCurPage, -1);
        }
    },

    goto : function (sHref, iDur) {
        this.tween.iStart = new Date() * 1;
        this.tween.iDur = iDur;
        this.tween.fromX = this.oPages.offsetLeft;
        this.tween.fromY = this.oPages.offsetTop;
        this.tween.iXPos   = this.aPages[sHref].iXPos - this.tween.fromX;
        this.tween.iYPos   = this.aPages[sHref].iYPos - this.tween.fromY;
        this.sTargPage = sHref;

        if (! this.bRunning)
            this.bRunning = window.setInterval(this.animate, 24);
    },

    animate : function () {
        var iCurTime = (new Date() * 1) - navi.tween.iStart;
        if (iCurTime &lt; navi.tween.iDur) {
            var iCur = Math.cos(Math.PI * (iCurTime / navi.tween.iDur)) - 1;
            navi.oPages.style.left = Math.round(-navi.tween.iXPos * .5 * iCur + navi.tween.fromX) + 'px';
            navi.oPages.style.top  = Math.round(-navi.tween.iYPos * .5 * iCur + navi.tween.fromY) + 'px';
        } else {
            navi.oPages.style.left = Math.round(navi.tween.fromX + navi.tween.iXPos) + 'px';
            navi.oPages.style.top  = Math.round(navi.tween.fromY + navi.tween.iYPos) + 'px';

            window.clearInterval(navi.bRunning);
            navi.bRunning = false;
            navi.sCurPage = navi.sTargPage;

            var i = 0; var p = null;
            while (p = navi.aLinks[i++]) {
                if (p.oObj.id == navi.sCurPage) {
                    if (p.a.className.indexOf('visited') &gt;= 0 ) {
                        p.a.className = p.a.className.replace('visited', 'active');
                    } else p.a.className += ' active';
                    p.visited = true;
                } else if (p.visited) {
                    p.a.className = p.a.className.replace('active', 'visited');
                }
            }

            if (navi.bHash) {
                if (navi.bUpdateH) {
                    navi.sOldH = navi.sCurPage;
                    window.location.hash = navi.sCurPage;
                }
                navi.bUpdateH = true;
            }
        }
    }
}

window.onload = function() { // page onload
    navi.init({parent_id: 'container', pages_id: 'pages', duration: 1000});
}
window.onkeydown = function(event){ // keyboard alerts
    switch (event.keyCode) {
        case 37: // Left key
            var iPage = navi.sCurPage.substring(4) * 1;
            iPage--;
            if (iPage &lt; 1) {
                iPage = 1;
            }
            navi.goto('page' + iPage, 1000);
            break;
        case 39: // Right key
            var iPage = navi.sCurPage.substring(4) * 1;
            iPage++;
            if (iPage &gt; 16) {
                iPage = 16;
            }
            navi.goto('page' + iPage, 1000);
            break;
    }
};
</pre><hr
/><h5 style="text-align: center;"><strong><a
title="Fullscreen Javascript Slide navigation - demo 215" href="http://www.script-tutorials.com/demos/215/index.html" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Fullscreen Javascript Slide navigation - package" href="http://www.script-tutorials.com/demos/215/source.zip" target="_blank" rel="nofollow">download in package</a></strong></h5><hr
/><h3>Conclusion</h3><p>Finally we have prepared interested result! I hope that this will interesting addition to your website. Don&#8217;t forget to tell thanks and leave a comment. Good luck!</p><div
class="shr-publisher-1350"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/css3-bottom-navigation-menu/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/170/thumb.png" alt="Creating a Toggle CSS3 Bottom Navigation Bar" /> <br
/> Creating a Toggle CSS3 Bottom Navigation Bar</a></li><li> <a
href="http://www.script-tutorials.com/css3-onclick-vertical-metal-menu/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/162/thumb.png" alt="Creating an Accordian like CSS3 Onclick Vertical Navigation" /> <br
/> Creating an Accordian like CSS3 Onclick Vertical Navigation</a></li><li> <a
href="http://www.script-tutorials.com/css3-metal-menu-with-icons/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/152/thumb.png" alt="Creating a Multilevel CSS3 Metal Navigation with icons" /> <br
/> Creating a Multilevel CSS3 Metal Navigation with icons</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/fullscreen-javascript-slide-navigation/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>HTML5 Face Builder</title><link>http://www.script-tutorials.com/html5-face-builder/</link> <comments>http://www.script-tutorials.com/html5-face-builder/#comments</comments> <pubDate>Mon, 12 Dec 2011 16:39:00 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[canvas]]></category> <category><![CDATA[face builder]]></category> <category><![CDATA[html5]]></category> <category><![CDATA[toy]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1295</guid> <description><![CDATA[HTML5 Face Builder This is another interesting application of HTML5. Today I have developed a little &#8216;toy&#8217;. This little toy can be enhanced into something big. Welcome to test new HTML5 tool &#8211; Face Builder (canvas). This tool will allow your members (visitors) to compose their faces, you can select through predefined elements (face, eyes, [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/html5-canvas-image-zoomer/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/167/thumb.png" alt="Creating an Image Zoomer in HTML5 Canvas" /> Creating an Image Zoomer in HTML5 Canvas</a></li><li> <a
href="http://www.script-tutorials.com/html5-animation-patterns-with-loops/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/194/thumb.png" alt="HTML5 animation &#8211; patterns with loops" /> HTML5 animation &#8211; patterns with loops</a></li><li> <a
href="http://www.script-tutorials.com/html5-canvas-image-effects-app/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/118/thumb.png" alt="Creating an Unbelievable HTML5 Canvas App for Online Image Enhancements" /> Creating an Unbelievable HTML5 Canvas App for Online Image Enhancements</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="HTML5 Face Builder" alt="HTML5 Face Builder" src="http://www.script-tutorials.com/demos/200/thumb.png"></div><p><strong>HTML5 Face Builder</strong><br
/> <br
/>This is another interesting application of HTML5. Today I have developed a little &#8216;toy&#8217;. This little toy can be enhanced into something big. Welcome to test new HTML5 tool &#8211; Face Builder (canvas). This tool will allow your members (visitors) to compose their faces, you can select through predefined elements (face, eyes, nose, mouth), and in end &#8211; you can &#8216;export&#8217; result into image (like crop tool).<br
/> <span
id="more-1295"></span><br
/></p><p>Here are our demo and downloadable package:</p><h5 style="text-align: center;"><strong><a
title="HTML5 Face Builder - demo 200" href="http://www.script-tutorials.com/demos/200/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="HTML5 Face Builder - package" href="http://www.script-tutorials.com/demos/200/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Ok, download the source files and lets start coding !</p><hr
/><h3>Step 1. HTML</h3><p>Small code with canvas element and blank image (for future exported image)</p><h4>index.html</h4><pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;HTML5 Face Builder | Script Tutorials&lt;/title&gt;

        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;script src=&quot;http://code.jquery.com/jquery-latest.min.js&quot;&gt;&lt;/script&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/script.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;header&gt;
            &lt;h2&gt;HTML5 image crop tool&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/html5-face-builder/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/header&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;canvas id=&quot;scene&quot; width=&quot;500&quot; height=&quot;500&quot;&gt;&lt;/canvas&gt;
            &lt;div id=&quot;results&quot;&gt;
                &lt;h2&gt;Use arrow keys to select your face details (up-down to select category, left-right to switch them), then click Spacebar to export as image.&lt;/h2&gt;
                &lt;img id=&quot;face_result&quot; /&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><h3>Step 2. HTML5 JS</h3><h4>js/script.js</h4><pre class="brush:js">
// inner variables
var canvas, ctx;
var oHead, oEye, oNose, oMouth;
var iSel = 0;
// -------------------------------------------------------------

// objects :
function Head(x, y, x2, y2, w, h, image) {
    this.x = x;
    this.y = y;
    this.x2 = x2;
    this.y2 = y2;
    this.w = w;
    this.h = h;
    this.image = image;
    this.iSpr = 0;
}
function Eye(x, y, x2, y2, w, h, image) {
    this.x = x;
    this.y = y;
    this.x2 = x2;
    this.y2 = y2;
    this.w = w;
    this.h = h;
    this.image = image;
    this.iSpr = 0;
}
function Nose(x, y, x2, y2, w, h, image) {
    this.x = x;
    this.y = y;
    this.x2 = x2;
    this.y2 = y2;
    this.w = w;
    this.h = h;
    this.image = image;
    this.iSpr = 0;
}
function Mouth(x, y, x2, y2, w, h, image) {
    this.x = x;
    this.y = y;
    this.x2 = x2;
    this.y2 = y2;
    this.w = w;
    this.h = h;
    this.image = image;
    this.iSpr = 0;
}
// -------------------------------------------------------------

// draw functions :
function clear() { // clear canvas function
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

function drawScene() { // main drawScene function
    clear(); // clear canvas

    // draw head
    ctx.drawImage(oHead.image, oHead.x2 + oHead.iSpr*oHead.w, oHead.y2, oHead.w, oHead.h, oHead.x, oHead.y, oHead.w, oHead.h);

    // draw eyes
    ctx.drawImage(oEye.image, oEye.x2 + oEye.iSpr*oEye.w, oEye.y2, oEye.w, oEye.h, oEye.x, oEye.y, oEye.w, oEye.h);

    // draw nose
    ctx.drawImage(oNose.image, oNose.x2 + oNose.iSpr*oNose.w, oNose.y2, oNose.w, oNose.h, oNose.x, oNose.y, oNose.w, oNose.h);

    // draw mouth
    ctx.drawImage(oMouth.image, oMouth.x2 + oMouth.iSpr*oMouth.w, oMouth.y2, oMouth.w, oMouth.h, oMouth.x, oMouth.y, oMouth.w, oMouth.h);

    // draw controls
    ctx.textAlign = 'center';
    ctx.fillStyle = '#000';

    ctx.font = '30px Verdana';
    if (iSel == 0)
        ctx.font = 'bold 30px Verdana';
    ctx.fillText('&lt; Head &gt;', 400, 80);

    ctx.font = '30px Verdana';
    if (iSel == 1)
        ctx.font = 'bold 30px Verdana';
    ctx.fillText('&lt; Eye &gt;', 400, 180);

    ctx.font = '30px Verdana';
    if (iSel == 2)
        ctx.font = 'bold 30px Verdana';
    ctx.fillText('&lt; Nose &gt;', 400, 280);

    ctx.font = '30px Verdana';
    if (iSel == 3)
        ctx.font = 'bold 30px Verdana';
    ctx.fillText('&lt; Mouth &gt;', 400, 380);
}

// -------------------------------------------------------------

// initialization
$(function(){
    canvas = document.getElementById('scene');
    ctx = canvas.getContext('2d');

    // initialization of dragon
    var oHeadImage = new Image();
    oHeadImage.src = 'images/image.png';
    oHeadImage.onload = function() {};

    oHead = new Head(0, 0, 0, 755, 300, 405, oHeadImage);
    oEye = new Eye(40, 70, 0, 120, 235, 80, oHeadImage);
    oNose = new Nose(70, 120, 0, 276, 180, 140, oHeadImage);
    oMouth = new Mouth(60, 260, 0, 546, 170, 120, oHeadImage);

    $(window).keydown(function(event){
        switch (event.keyCode) {
            case 38: // Up key
                iSel--;
                if (iSel &lt; 0) {
                    iSel = 3;
                }
                break;
            case 40: // Up key
                iSel++;
                if (iSel &gt;= 4) {
                    iSel = 0;
                }
                break;
            case 37: // Left key

                // update sprite positions
                if (iSel == 0) {
                    oHead.iSpr--;
                    if (oHead.iSpr &lt; 0) {
                        oHead.iSpr = 3;
                    }
                }
                if (iSel == 1) {
                    oEye.iSpr--;
                    if (oEye.iSpr &lt; 0) {
                        oEye.iSpr = 4;
                    }
                }
                if (iSel == 2) {
                    oNose.iSpr--;
                    if (oNose.iSpr &lt; 0) {
                        oNose.iSpr = 4;
                    }
                }
                if (iSel == 3) {
                    oMouth.iSpr--;
                    if (oMouth.iSpr &lt; 0) {
                        oMouth.iSpr = 4;
                    }
                }
                break;
            case 39: // Right key

                // update sprite positions
                if (iSel == 0) {
                    oHead.iSpr++;
                    if (oHead.iSpr &gt;= 4) {
                        oHead.iSpr = 0;
                    }
                }
                if (iSel == 1) {
                    oEye.iSpr++;
                    if (oEye.iSpr &gt;= 5) {
                        oEye.iSpr = 0;
                    }
                }
                if (iSel == 2) {
                    oNose.iSpr++;
                    if (oNose.iSpr &gt;= 5) {
                        oNose.iSpr = 0;
                    }
                }
                if (iSel == 3) {
                    oMouth.iSpr++;
                    if (oMouth.iSpr &gt;= 5) {
                        oMouth.iSpr = 0;
                    }
                }
                break;

            case 32: // Spacebar key - export results
                var temp_ctx, temp_canvas;
                temp_canvas = document.createElement('canvas');
                temp_ctx = temp_canvas.getContext('2d');
                temp_canvas.width = 360;
                temp_canvas.height = 410;

                // draw head
                temp_ctx.drawImage(oHead.image, oHead.iSpr*oHead.w, oHead.y2, oHead.w, oHead.h, oHead.x, oHead.y, oHead.w, oHead.h);

                // draw eyes
                temp_ctx.drawImage(oEye.image, oEye.iSpr*oEye.w, oEye.y2, oEye.w, oEye.h, oEye.x, oEye.y, oEye.w, oEye.h);

                // draw nose
                temp_ctx.drawImage(oNose.image, oNose.iSpr*oNose.w, oNose.y2, oNose.w, oNose.h, oNose.x, oNose.y, oNose.w, oNose.h);

                // draw mouth
                temp_ctx.drawImage(oMouth.image, oMouth.iSpr*oMouth.w, oMouth.y2, oMouth.w, oMouth.h, oMouth.x, oMouth.y, oMouth.w, oMouth.h);

                var vData = temp_canvas.toDataURL();
                $('#face_result').attr('src', vData);
                break;
        }
    }); 

    setInterval(drawScene, 40); // loop drawScene
});
</pre><p>Most of code is already commented. So I will hope that you will understand all this code. If not &#8211; you always can ask me any related questions.</p><hr
/><h5 style="text-align: center;"><strong><a
title="HTML5 Face Builder - demo 200" href="http://www.script-tutorials.com/demos/200/index.html" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="HTML5 Face Builder - package" href="http://www.script-tutorials.com/demos/200/source.zip" target="_blank" rel="nofollow">download in package</a></strong></h5><hr
/><h3>Conclusion</h3><p>Welcome back to read something new and interesting about HTML5. Good luck in your projects.</p><div
class="shr-publisher-1295"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/html5-canvas-image-zoomer/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/167/thumb.png" alt="Creating an Image Zoomer in HTML5 Canvas" /> <br
/> Creating an Image Zoomer in HTML5 Canvas</a></li><li> <a
href="http://www.script-tutorials.com/html5-animation-patterns-with-loops/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/194/thumb.png" alt="HTML5 animation &#8211; patterns with loops" /> <br
/> HTML5 animation &#8211; patterns with loops</a></li><li> <a
href="http://www.script-tutorials.com/html5-canvas-image-effects-app/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/118/thumb.png" alt="Creating an Unbelievable HTML5 Canvas App for Online Image Enhancements" /> <br
/> Creating an Unbelievable HTML5 Canvas App for Online Image Enhancements</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/html5-face-builder/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Pure HTML5 file upload</title><link>http://www.script-tutorials.com/pure-html5-file-upload/</link> <comments>http://www.script-tutorials.com/pure-html5-file-upload/#comments</comments> <pubDate>Fri, 09 Dec 2011 17:34:37 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[ajaxy]]></category> <category><![CDATA[html5]]></category> <category><![CDATA[photo upload]]></category> <category><![CDATA[preview]]></category> <category><![CDATA[upload]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1291</guid> <description><![CDATA[Pure HTML5 file upload Today we will be developing a great HTML5 file upload form with progress bar and preview (at client-side). We have already gave you jQuery based solution, but today&#8217;s application don&#8217;t require jQuery at all. All made in pure HTML5 Javascript. I&#8217;m going to use FileReader (html5) to implement live preview (without [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/ajax-file-upload-methods/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="Creating Ajax based file uploaders" /> Creating Ajax based file uploaders</a></li><li> <a
href="http://www.script-tutorials.com/html5-image-effects-app-adding-horizontal-flip/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/149/thumb.png" alt="Creating HTML5 Image Effects App &#8211; Adding Horizontal Flip" /> Creating HTML5 Image Effects App &#8211; Adding Horizontal Flip</a></li><li> <a
href="http://www.script-tutorials.com/html5-game-development-navigating-your-spaceship-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/166/thumb.png" alt="HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3" /> HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Pure HTML5 file upload" alt="Pure HTML5 file upload" src="http://www.script-tutorials.com/demos/199/thumb.png"></div><p><strong>Pure HTML5 file upload</strong><br
/> <br
/>Today we will be developing a great HTML5 file upload form with progress bar and preview (at client-side). We have already gave you jQuery based solution, but today&#8217;s application don&#8217;t require jQuery at all. All made in pure HTML5 Javascript. I&#8217;m going to use FileReader (html5) to implement live preview (without uploading to server), and, going to use XMLHttpRequest to send data to server.<br
/> <span
id="more-1291"></span><br
/></p><p>Here are our demo and downloadable package:</p><h5 style="text-align: center;"><strong><a
title="Pure HTML5 file upload - demo 199" href="http://www.script-tutorials.com/demos/199/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Pure HTML5 file upload - package" href="http://www.script-tutorials.com/demos/199/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Ok, download the sources and lets begin !</p><hr
/><h3>Step 1. HTML</h3><p>At this page you can see out form for upload images</p><h4>index.html</h4><pre class="brush:html">
<!DOCTYPE html>
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;Pure HTML5 file upload | Script Tutorials&lt;/title&gt;
        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;script src=&quot;js/script.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;header&gt;
            &lt;h2&gt;Pure HTML5 file upload&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/pure-html5-file-upload/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/header&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;div class=&quot;contr&quot;&gt;&lt;h2&gt;You can select the file (image) and click Upload button&lt;/h2&gt;&lt;/div&gt;

            &lt;div class=&quot;upload_form_cont&quot;&gt;
                &lt;form id=&quot;upload_form&quot; enctype=&quot;multipart/form-data&quot; method=&quot;post&quot; action=&quot;upload.php&quot;&gt;
                    &lt;div&gt;
                        &lt;div&gt;&lt;label for=&quot;image_file&quot;&gt;Please select image file&lt;/label&gt;&lt;/div&gt;
                        &lt;div&gt;&lt;input type=&quot;file&quot; name=&quot;image_file&quot; id=&quot;image_file&quot; onchange=&quot;fileSelected();&quot; /&gt;&lt;/div&gt;
                    &lt;/div&gt;
                    &lt;div&gt;
                        &lt;input type=&quot;button&quot; value=&quot;Upload&quot; onclick=&quot;startUploading()&quot; /&gt;
                    &lt;/div&gt;
                    &lt;div id=&quot;fileinfo&quot;&gt;
                        &lt;div id=&quot;filename&quot;&gt;&lt;/div&gt;
                        &lt;div id=&quot;filesize&quot;&gt;&lt;/div&gt;
                        &lt;div id=&quot;filetype&quot;&gt;&lt;/div&gt;
                        &lt;div id=&quot;filedim&quot;&gt;&lt;/div&gt;
                    &lt;/div&gt;
                    &lt;div id=&quot;error&quot;&gt;You should select valid image files only!&lt;/div&gt;
                    &lt;div id=&quot;error2&quot;&gt;An error occurred while uploading the file&lt;/div&gt;
                    &lt;div id=&quot;abort&quot;&gt;The upload has been canceled by the user or the browser dropped the connection&lt;/div&gt;
                    &lt;div id=&quot;warnsize&quot;&gt;Your file is very big. We can't accept it. Please select more small file&lt;/div&gt;

                    &lt;div id=&quot;progress_info&quot;&gt;
                        &lt;div id=&quot;progress&quot;&gt;&lt;/div&gt;
                        &lt;div id=&quot;progress_percent&quot;&gt;&amp;nbsp;&lt;/div&gt;
                        &lt;div class=&quot;clear_both&quot;&gt;&lt;/div&gt;
                        &lt;div&gt;
                            &lt;div id=&quot;speed&quot;&gt;&amp;nbsp;&lt;/div&gt;
                            &lt;div id=&quot;remaining&quot;&gt;&amp;nbsp;&lt;/div&gt;
                            &lt;div id=&quot;b_transfered&quot;&gt;&amp;nbsp;&lt;/div&gt;
                            &lt;div class=&quot;clear_both&quot;&gt;&lt;/div&gt;
                        &lt;/div&gt;
                        &lt;div id=&quot;upload_response&quot;&gt;&lt;/div&gt;
                    &lt;/div&gt;
                &lt;/form&gt;

                &lt;img id=&quot;preview&quot; /&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><h3>Step 2. CSS</h3><h4>css/main.css</h4><p>I have selected all necessary styles for our html5 upload form</p><h4>css/main.css</h4><pre class="brush:css">
.upload_form_cont {
    background: -moz-linear-gradient(#ffffff, #f2f2f2);
    background: -ms-linear-gradient(#ffffff, #f2f2f2);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ffffff), color-stop(100%, #f2f2f2));
    background: -webkit-linear-gradient(#ffffff, #f2f2f2);
    background: -o-linear-gradient(#ffffff, #f2f2f2);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f2f2f2');
    -ms-filter: &quot;progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f2f2f2')&quot;;
    background: linear-gradient(#ffffff, #f2f2f2);

    color:#000;
    overflow:hidden;
}
#upload_form {
    float:left;
    padding:20px;
    width:700px;
}
#preview {
    background-color:#fff;
    display:block;
    float:right;
    width:200px;
}
#upload_form &gt; div {
    margin-bottom:10px;
}
#speed,#remaining {
    float:left;
    width:100px;
}
#b_transfered {
    float:right;
    text-align:right;
}
.clear_both {
    clear:both;
}
input {
    border-radius:10px;
    -moz-border-radius:10px;
    -ms-border-radius:10px;
    -o-border-radius:10px;
    -webkit-border-radius:10px;

    border:1px solid #ccc;
    font-size:14pt;
    padding:5px 10px;
}
input[type=button] {
    background: -moz-linear-gradient(#ffffff, #dfdfdf);
    background: -ms-linear-gradient(#ffffff, #dfdfdf);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ffffff), color-stop(100%, #dfdfdf));
    background: -webkit-linear-gradient(#ffffff, #dfdfdf);
    background: -o-linear-gradient(#ffffff, #dfdfdf);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#dfdfdf');
    -ms-filter: &quot;progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#dfdfdf')&quot;;
    background: linear-gradient(#ffffff, #dfdfdf);
}
#image_file {
    width:400px;
}
#progress_info {
    font-size:10pt;
}
#fileinfo,#error,#error2,#abort,#warnsize {
    color:#aaa;
    display:none;
    font-size:10pt;
    font-style:italic;
    margin-top:10px;
}
#progress {
    border:1px solid #ccc;
    display:none;
    float:left;
    height:14px;

    border-radius:10px;
    -moz-border-radius:10px;
    -ms-border-radius:10px;
    -o-border-radius:10px;
    -webkit-border-radius:10px;

    background: -moz-linear-gradient(#66cc00, #4b9500);
    background: -ms-linear-gradient(#66cc00, #4b9500);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #66cc00), color-stop(100%, #4b9500));
    background: -webkit-linear-gradient(#66cc00, #4b9500);
    background: -o-linear-gradient(#66cc00, #4b9500);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#66cc00', endColorstr='#4b9500');
    -ms-filter: &quot;progid:DXImageTransform.Microsoft.gradient(startColorstr='#66cc00', endColorstr='#4b9500')&quot;;
    background: linear-gradient(#66cc00, #4b9500);
}
#progress_percent {
    float:right;
}
#upload_response {
    margin-top: 10px;
    padding: 20px;
    overflow: hidden;
    display: none;
    border: 1px solid #ccc;

    border-radius:10px;
    -moz-border-radius:10px;
    -ms-border-radius:10px;
    -o-border-radius:10px;
    -webkit-border-radius:10px;

    box-shadow: 0 0 5px #ccc;
    background: -moz-linear-gradient(#bbb, #eee);
    background: -ms-linear-gradient(#bbb, #eee);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #bbb), color-stop(100%, #eee));
    background: -webkit-linear-gradient(#bbb, #eee);
    background: -o-linear-gradient(#bbb, #eee);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#bbb', endColorstr='#eee');
    -ms-filter: &quot;progid:DXImageTransform.Microsoft.gradient(startColorstr='#bbb', endColorstr='#eee')&quot;;
    background: linear-gradient(#bbb, #eee);
}
</pre><h3>Step 3. HTML5 JS</h3><h4>js/script.js</h4><pre class="brush:js">
// common variables
var iBytesUploaded = 0;
var iBytesTotal = 0;
var iPreviousBytesLoaded = 0;
var iMaxFilesize = 1048576; // 1MB
var oTimer = 0;
var sResultFileSize = '';

function secondsToTime(secs) { // we will use this function to convert seconds in normal time format
    var hr = Math.floor(secs / 3600);
    var min = Math.floor((secs - (hr * 3600))/60);
    var sec = Math.floor(secs - (hr * 3600) -  (min * 60));

    if (hr &lt; 10) {hr = &quot;0&quot; + hr; }
    if (min &lt; 10) {min = &quot;0&quot; + min;}
    if (sec &lt; 10) {sec = &quot;0&quot; + sec;}
    if (hr) {hr = &quot;00&quot;;}
    return hr + ':' + min + ':' + sec;
};

function bytesToSize(bytes) {
    var sizes = ['Bytes', 'KB', 'MB'];
    if (bytes == 0) return 'n/a';
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};

function fileSelected() {

    // hide different warnings
    document.getElementById('upload_response').style.display = 'none';
    document.getElementById('error').style.display = 'none';
    document.getElementById('error2').style.display = 'none';
    document.getElementById('abort').style.display = 'none';
    document.getElementById('warnsize').style.display = 'none';

    // get selected file element
    var oFile = document.getElementById('image_file').files[0];

    // filter for image files
    var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
    if (! rFilter.test(oFile.type)) {
        document.getElementById('error').style.display = 'block';
        return;
    }

    // little test for filesize
    if (oFile.size &gt; iMaxFilesize) {
        document.getElementById('warnsize').style.display = 'block';
        return;
    }

    // get preview element
    var oImage = document.getElementById('preview');

    // prepare HTML5 FileReader
    var oReader = new FileReader();
        oReader.onload = function(e){

        // e.target.result contains the DataURL which we will use as a source of the image
        oImage.src = e.target.result;

        oImage.onload = function () { // binding onload event

            // we are going to display some custom image information here
            sResultFileSize = bytesToSize(oFile.size);
            document.getElementById('fileinfo').style.display = 'block';
            document.getElementById('filename').innerHTML = 'Name: ' + oFile.name;
            document.getElementById('filesize').innerHTML = 'Size: ' + sResultFileSize;
            document.getElementById('filetype').innerHTML = 'Type: ' + oFile.type;
            document.getElementById('filedim').innerHTML = 'Dimension: ' + oImage.naturalWidth + ' x ' + oImage.naturalHeight;
        };
    };

    // read selected file as DataURL
    oReader.readAsDataURL(oFile);
}

function startUploading() {
    // cleanup all temp states
    iPreviousBytesLoaded = 0;
    document.getElementById('upload_response').style.display = 'none';
    document.getElementById('error').style.display = 'none';
    document.getElementById('error2').style.display = 'none';
    document.getElementById('abort').style.display = 'none';
    document.getElementById('warnsize').style.display = 'none';
    document.getElementById('progress_percent').innerHTML = '';
    var oProgress = document.getElementById('progress');
    oProgress.style.display = 'block';
    oProgress.style.width = '0px';

    // get form data for POSTing
    //var vFD = document.getElementById('upload_form').getFormData(); // for FF3
    var vFD = new FormData(document.getElementById('upload_form')); 

    // create XMLHttpRequest object, adding few event listeners, and POSTing our data
    var oXHR = new XMLHttpRequest();
    oXHR.upload.addEventListener('progress', uploadProgress, false);
    oXHR.addEventListener('load', uploadFinish, false);
    oXHR.addEventListener('error', uploadError, false);
    oXHR.addEventListener('abort', uploadAbort, false);
    oXHR.open('POST', 'upload.php');
    oXHR.send(vFD);

    // set inner timer
    oTimer = setInterval(doInnerUpdates, 300);
}

function doInnerUpdates() { // we will use this function to display upload speed
    var iCB = iBytesUploaded;
    var iDiff = iCB - iPreviousBytesLoaded;

    // if nothing new loaded - exit
    if (iDiff == 0)
        return;

    iPreviousBytesLoaded = iCB;
    iDiff = iDiff * 2;
    var iBytesRem = iBytesTotal - iPreviousBytesLoaded;
    var secondsRemaining = iBytesRem / iDiff;

    // update speed info
    var iSpeed = iDiff.toString() + 'B/s';
    if (iDiff &gt; 1024 * 1024) {
        iSpeed = (Math.round(iDiff * 100/(1024*1024))/100).toString() + 'MB/s';
    } else if (iDiff &gt; 1024) {
        iSpeed =  (Math.round(iDiff * 100/1024)/100).toString() + 'KB/s';
    }

    document.getElementById('speed').innerHTML = iSpeed;
    document.getElementById('remaining').innerHTML = '| ' + secondsToTime(secondsRemaining);
}

function uploadProgress(e) { // upload process in progress
    if (e.lengthComputable) {
        iBytesUploaded = e.loaded;
        iBytesTotal = e.total;
        var iPercentComplete = Math.round(e.loaded * 100 / e.total);
        var iBytesTransfered = bytesToSize(iBytesUploaded);

        document.getElementById('progress_percent').innerHTML = iPercentComplete.toString() + '%';
        document.getElementById('progress').style.width = (iPercentComplete * 4).toString() + 'px';
        document.getElementById('b_transfered').innerHTML = iBytesTransfered;
        if (iPercentComplete == 100) {
            var oUploadResponse = document.getElementById('upload_response');
            oUploadResponse.innerHTML = '&lt;h1&gt;Please wait...processing&lt;/h1&gt;';
            oUploadResponse.style.display = 'block';
        }
    } else {
        document.getElementById('progress').innerHTML = 'unable to compute';
    }
}

function uploadFinish(e) { // upload successfully finished
    var oUploadResponse = document.getElementById('upload_response');
    oUploadResponse.innerHTML = e.target.responseText;
    oUploadResponse.style.display = 'block';

    document.getElementById('progress_percent').innerHTML = '100%';
    document.getElementById('progress').style.width = '400px';
    document.getElementById('filesize').innerHTML = sResultFileSize;
    document.getElementById('remaining').innerHTML = '| 00:00:00';

    clearInterval(oTimer);
}

function uploadError(e) { // upload error
    document.getElementById('error2').style.display = 'block';
    clearInterval(oTimer);
}  

function uploadAbort(e) { // upload abort
    document.getElementById('abort').style.display = 'block';
    clearInterval(oTimer);
}
</pre><p>Most of code is already commented. So I will hope that you will understand all this code. Anyway &#8211; how it working: when we select file &#8211; function &#8216;fileSelected&#8217; is executing. We filter all unnecessary formats (allow to upload next formats: bmp, gif, jpg, png, tif), in case of huge file &#8211; we will draw warning message. Then, through FileReader::readAsDataURL we will draw live preview of selected file. Plus, we will display another information about image: its name, size, type, and dimensions. Process of uploading is a little complicated. But generally, we have to prepare XMLHttpRequest object, add event listeners to next events: progress, load, error and abort. And after &#8211; post form data (I have used FormData class) to our &#8216;upload.php&#8217; receiver.</p><h3>Step 4. PHP</h3><h4>upload.php</h4><pre class="brush:js">
&lt;?php

function bytesToSize1024($bytes, $precision = 2) {
    $unit = array('B','KB','MB');
    return @round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $precision).' '.$unit[$i];
}

$sFileName = $_FILES['image_file']['name'];
$sFileType = $_FILES['image_file']['type'];
$sFileSize = bytesToSize1024($_FILES['image_file']['size'], 1);

echo &lt;&lt;&lt;EOF
&lt;p&gt;Your file: {$sFileName} has been successfully received.&lt;/p&gt;
&lt;p&gt;Type: {$sFileType}&lt;/p&gt;
&lt;p&gt;Size: {$sFileSize}&lt;/p&gt;
EOF;
</pre><p>As you can see &#8211; I&#8217;m not uploading file. But, &#8216;echo&#8217; back all info about accepted file. This information will appear in our &lt;div id=&quot;upload_response&quot;&gt;&lt;/div&gt; element.</p><hr
/><h5 style="text-align: center;"><strong><a
title="Pure HTML5 file upload - demo 199" href="http://www.script-tutorials.com/demos/199/index.html" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Pure HTML5 file upload - package" href="http://www.script-tutorials.com/demos/199/source.zip" target="_blank" rel="nofollow">download in package</a></strong></h5><hr
/><h3>Conclusion</h3><p>Welcome back to read new awesome and unique articles about HTML5. Good luck!</p><div
class="shr-publisher-1291"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/ajax-file-upload-methods/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="Creating Ajax based file uploaders" /> <br
/> Creating Ajax based file uploaders</a></li><li> <a
href="http://www.script-tutorials.com/html5-image-effects-app-adding-horizontal-flip/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/149/thumb.png" alt="Creating HTML5 Image Effects App &#8211; Adding Horizontal Flip" /> <br
/> Creating HTML5 Image Effects App &#8211; Adding Horizontal Flip</a></li><li> <a
href="http://www.script-tutorials.com/html5-game-development-navigating-your-spaceship-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/166/thumb.png" alt="HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3" /> <br
/> HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/pure-html5-file-upload/feed/</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>HTML5 animation &#8211; patterns with loops</title><link>http://www.script-tutorials.com/html5-animation-patterns-with-loops/</link> <comments>http://www.script-tutorials.com/html5-animation-patterns-with-loops/#comments</comments> <pubDate>Sat, 03 Dec 2011 18:22:32 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[canvas]]></category> <category><![CDATA[coding]]></category> <category><![CDATA[html5]]></category> <category><![CDATA[HTML5 animation]]></category> <category><![CDATA[tutorial]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1268</guid> <description><![CDATA[HTML5 animation &#8211; patterns with loops I have prepared new HTML5 tutorial for you. This is not quite regular &#8216;html5 game development&#8217; tutorial, but I like to show you another demonstration of html5 canvas animation. We will create patterns with loops and animate it. Today I have prepared nice demo with the sun and with [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/html5-canvas-image-zoomer/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/167/thumb.png" alt="Creating an Image Zoomer in HTML5 Canvas" /> Creating an Image Zoomer in HTML5 Canvas</a></li><li> <a
href="http://www.script-tutorials.com/html5-game-development-navigating-your-spaceship-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/166/thumb.png" alt="HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3" /> HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3</a></li><li> <a
href="http://www.script-tutorials.com/html5-canvas-creating-your-own-paint-program/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/173/thumb.png" alt="HTML5 canvas &#8211; Creating Your Own Paint Program" /> HTML5 canvas &#8211; Creating Your Own Paint Program</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="HTML5 animation - patterns with loops" alt="HTML5 animation - patterns with loops" src="http://www.script-tutorials.com/demos/194/thumb.png"></div><p><strong>HTML5 animation &#8211; patterns with loops</strong><br
/> <br
/>I have prepared new HTML5 tutorial for you. This is not quite regular &#8216;html5 game development&#8217; tutorial, but I like to show you another demonstration of html5 canvas animation. We will create patterns with loops and animate it. Today I have prepared nice demo with the sun and with three cars.<br
/> <span
id="more-1268"></span><br
/></p><p>Here are our demo and downloadable package:</p><h5 style="text-align: center;"><strong><a
title="HTML5 animation - patterns with loops - demo 194" href="http://www.script-tutorials.com/demos/194/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="HTML5 animation - patterns with loops - package" href="http://www.script-tutorials.com/demos/194/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Ok, download the source files and lets start coding !</p><hr
/><h3>Step 1. HTML</h3><p>Small code with canvas element (where we are going to experiment)</p><h4>index.html</h4><pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;HTML5 animation - patterns with loops | Script Tutorials&lt;/title&gt;
        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/script.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;header&gt;
            &lt;h2&gt;HTML5 animation - patterns with loops&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/html5-animation-patterns-with-loops/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/header&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;div class=&quot;contr&quot;&gt;
                &lt;input type=&quot;radio&quot; name=&quot;mode&quot; onchange=&quot;bPlay = false&quot; /&gt;&lt;label&gt;Pause&lt;/label&gt;
                &lt;input type=&quot;radio&quot; name=&quot;mode&quot; onchange=&quot;bPlay = true&quot; checked /&gt;&lt;label&gt;Play&lt;/label&gt;
            &lt;/div&gt;
            &lt;canvas id=&quot;panel&quot; width=&quot;800&quot; height=&quot;600&quot;&gt;&lt;/canvas&gt;
        &lt;/div&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><h3>Step 2. CSS</h3><h4>css/main.css</h4><p>We are going to skip of publishing styles today again (no need).</p><h3>Step 3. JS</h3><h4>js/script.js</h4><pre class="brush:js">
// variables
var canvas, ctx;
var bPlay = true;
var theSun;
var theCar1, theCar2, theCar3;

// define Sun constructor
function Sun(iCenterX, iCenterY, iRad, iRaysCnt, sRayColor, sSunColor){
    this.iCenterX = iCenterX;
    this.iCenterY = iCenterY;
    this.iRad = iRad;
    this.iRaysCnt = iRaysCnt;
    this.sRayColor = sRayColor;
    this.sSunColor = sSunColor;
    this.iExAngle = 0;
    this.bDir = true;
}

// Define Sun draw method
Sun.prototype.draw = function(){

    // change angle
    if (this.bDir) {
        this.iExAngle += 0.05;
    } else {
        this.iExAngle -= 0.05;
    }
    if (this.iExAngle &gt; 3 || this.iExAngle &lt; -3) {
        this.bDir = ! this.bDir;
    }

    // draw rays
    ctx.beginPath();
    for (var n = 0; n &lt; this.iRaysCnt; n++) {
        var iAng1 = ((Math.PI * 2) / this.iRaysCnt) * (n + 1);
        var iAng2 = ((Math.PI * 2) / this.iRaysCnt) * (n);
        var iAng3 = ((Math.PI * 2) / this.iRaysCnt) * (n+0.5);
        var x1 = (this.iRad * Math.sin(iAng1 + this.iExAngle)) + this.iCenterX;
        var y1 = (this.iRad * Math.cos(iAng1 + this.iExAngle)) + this.iCenterY;
        var x2 = (this.iRad * Math.sin(iAng2 + this.iExAngle)) + this.iCenterX;
        var y2 = (this.iRad * Math.cos(iAng2 + this.iExAngle)) + this.iCenterY;
        var x3 = (2 * this.iRad * Math.sin(iAng3 + this.iExAngle)) + this.iCenterX;
        var y3 = (2 * this.iRad * Math.cos(iAng3 + this.iExAngle)) + this.iCenterY;

        ctx.moveTo(x1, y1);
        ctx.lineTo(x3, y3);
        ctx.lineTo(x2, y2);
    }
    ctx.closePath();

    // fill rays with color
    ctx.fillStyle = this.sRayColor;
    ctx.fill();

    // draw sun center
    ctx.beginPath();
    ctx.arc(this.iCenterX, this.iCenterY, this.iRad, 0, 2 * Math.PI, false);
    ctx.fillStyle = this.sSunColor;
    ctx.fill();
};

// define CarWheel constructor
function CarWheel(iCenterX, iCenterY, iRad, iCnt, iSpeed, sColor1, sColor2, sColor3){
    this.iCenterX = iCenterX;
    this.iCenterY = iCenterY;
    this.iRad = iRad;
    this.iCnt = iCnt;
    this.iSpeed = iSpeed;
    this.sColor1 = sColor1;
    this.sColor2 = sColor2;
    this.sColor3 = sColor3;
    this.iAngle = 0;
}

// Define CarWheel draw method
CarWheel.prototype.draw = function(){
    this.iAngle += 0.1 * this.iSpeed / 2;
    this.iCenterX += this.iSpeed;

    // draw wheel details
    ctx.beginPath();
    for (var n = 0; n &lt; this.iCnt; n++) {
        var theta1 = ((Math.PI * 2) / this.iCnt) * (n + 1);
        var theta2 = ((Math.PI * 2) / this.iCnt) * (n);

        var x1 = (this.iRad * Math.sin(theta1-this.iAngle)) + this.iCenterX;
        var y1 = (this.iRad * Math.cos(theta1-this.iAngle)) + this.iCenterY;
        var x2 = (this.iRad * Math.sin(theta2-this.iAngle)) + this.iCenterX;
        var y2 = (this.iRad * Math.cos(theta2-this.iAngle)) + this.iCenterY;

        ctx.moveTo(this.iCenterX, this.iCenterY);
        ctx.bezierCurveTo(x1, y1, x2, y2, this.iCenterX, this.iCenterY);
    }
    ctx.closePath();

    // fill
    ctx.fillStyle = this.sColor2;
    ctx.fill();

    // stroke
    ctx.lineWidth = 1;
    ctx.strokeStyle = this.sColor1;
    ctx.stroke();

    // draw center
    ctx.beginPath();
    ctx.arc(this.iCenterX, this.iCenterY, this.iRad/2.5, 0, 2 * Math.PI, false);
    ctx.closePath();
    ctx.fillStyle = this.sColor3;
    ctx.fill();
};

// define Car constructor
function Car(iPosX, iPosY, iSpeed, iWidth, iHeight){
    this.iPosX = iPosX;
    this.iPosY = iPosY;
    this.iSpeed = iSpeed;
    this.iWidth = iWidth;
    this.iHeight = iHeight;

    this.theWheel1 = new CarWheel(this.iPosX + 41, this.iPosY + 52, 30, 8, this.iSpeed, 'black', 'brown', '#5e5e5e');
    this.theWheel2 = new CarWheel(this.iPosX + 191, this.iPosY + 52, 30, 8, this.iSpeed, 'black', 'brown', '#5e5e5e');

    // load image for car
    this.imageObj = new Image();
    this.imageObj.onload = function(){};
    this.imageObj.src = 'images/car.png';
}

// Define Car draw method
Car.prototype.draw = function(){
    this.iPosX += this.iSpeed;
    if (this.iPosX &gt; ctx.canvas.width /*+ this.iWidth*/) {
        this.iPosX = -this.iWidth;

        this.theWheel1.iCenterX = this.iPosX + 41;
        this.theWheel2.iCenterX = this.iPosX + 191;
        this.theWheel1.iAngle = 0;
        this.theWheel2.iAngle = 0;
    }

    // draw car image
    ctx.drawImage(this.imageObj, this.iPosX, this.iPosY, this.iWidth, this.iHeight);

    // and animated wheels
    this.theWheel1.draw();
    this.theWheel2.draw();
};

// drawing functions
function clear() { // clear canvas function
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

function drawScene() { // main drawScene function
    if (bPlay == 1) {
        clear(); // clear canvas

        // draw animated objects
        theSun.draw();
        theCar1.draw();
        theCar2.draw();
        theCar3.draw();
    }
}

function getRand(x, y) {
    return Math.floor(Math.random()*y)+x;
}

// binding onload event
if (window.attachEvent) {
    window.attachEvent('onload', main_init);
} else {
    if(window.onload) {
        var curronload = window.onload;
        var newonload = function() {
            curronload();
            main_init();
        };
        window.onload = newonload;
    } else {
        window.onload = main_init;
    }
}

function main_init() {

    // create canvas and context objects
    canvas = document.getElementById('panel');
    ctx = canvas.getContext('2d');

    // initialization of animated objects
    theSun = new Sun(725, 100, 25, 10, 'red', 'yellow');
    theCar1 = new Car(0, 300, 4, 226, 66);
    theCar2 = new Car(100, 400, 3, 226, 66);
    theCar3 = new Car(200, 500, 2, 226, 66);

    setInterval(drawScene, 40); // loop drawScene
}
</pre><p>Exactly 200 lines of code <img
src='http://www.script-tutorials.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> Here you can see three kind of objects (classes): Sun, Car and CarWheel. Each type have own constructor, own set of properties and Draw function. Sun rays we will draw as triangles. Car itself, consist of image and two wheels. Sun and Wheels uses patterns with loops. To create the sun (as example) we can create a loop with X iterations (where X is amount of rays or sectors). And, we will draw each ray separately (in loop).</p><hr
/><h5 style="text-align: center;"><strong><a
title="HTML5 animation - patterns with loops - demo 194" href="http://www.script-tutorials.com/demos/194/index.html" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="HTML5 animation - patterns with loops - package" href="http://www.script-tutorials.com/demos/194/source.zip" target="_blank" rel="nofollow">download in package</a></strong></h5><hr
/><h3>Conclusion</h3><p>Welcome back to read something new and interesting about HTML5. Good luck in your projects.</p><div
class="shr-publisher-1268"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/html5-canvas-image-zoomer/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/167/thumb.png" alt="Creating an Image Zoomer in HTML5 Canvas" /> <br
/> Creating an Image Zoomer in HTML5 Canvas</a></li><li> <a
href="http://www.script-tutorials.com/html5-game-development-navigating-your-spaceship-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/166/thumb.png" alt="HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3" /> <br
/> HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3</a></li><li> <a
href="http://www.script-tutorials.com/html5-canvas-creating-your-own-paint-program/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/173/thumb.png" alt="HTML5 canvas &#8211; Creating Your Own Paint Program" /> <br
/> HTML5 canvas &#8211; Creating Your Own Paint Program</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/html5-animation-patterns-with-loops/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>HTML5 Game Development &#8211; Lesson 4</title><link>http://www.script-tutorials.com/html5-game-development-lesson-4/</link> <comments>http://www.script-tutorials.com/html5-game-development-lesson-4/#comments</comments> <pubDate>Mon, 21 Nov 2011 16:32:01 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1227</guid> <description><![CDATA[HTML5 Game Development &#8211; Lesson 4 Today we continue a series of articles on game development in HTML5 using canvas. Today we going to learn next elements: animation with sprites and basic work with sound. In our demonstration you will see a flying dragon. We will hear the sounds of wings all time (we will [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/html5-game-development-navigating-your-spaceship-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/166/thumb.png" alt="HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3" /> HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3</a></li><li> <a
href="http://www.script-tutorials.com/html5-game-development-lesson-2/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/157/thumb.png" alt="HTML5 Game Development &#8211; Lesson 2" /> HTML5 Game Development &#8211; Lesson 2</a></li><li> <a
href="http://www.script-tutorials.com/html5-game-development-lesson-5/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/205/thumb.png" alt="HTML5 Game Development &#8211; Lesson 5" /> HTML5 Game Development &#8211; Lesson 5</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="HTML5 Game Development - Lesson 4" alt="HTML5 Game Development - Lesson 4" src="http://www.script-tutorials.com/demos/186/thumb.png"></div><p><strong>HTML5 Game Development &#8211; Lesson 4</strong><br
/> <br
/>Today we continue a series of articles on game development in HTML5 using canvas. Today we going to learn next elements: animation with sprites and basic work with sound. In our demonstration you will see a flying dragon. We will hear the sounds of wings all time (we will loop this sound), and another sound &#8211; dragon&#8217;s roar (on mouseup event). And finally we will teach our dragon be closer to the mouse cursor (when we hold down the mouse).<br
/> <br
/>Our previous article you can read here: <a
href="http://www.script-tutorials.com/html5-game-development-navigating-your-spaceship-lesson-3/">Developing Your First HTML5 Game – Lesson 3</a>. Our new script is new enhanced version of previous one.<br
/> <span
id="more-1227"></span><br
/></p><p>Here are our demo and downloadable package:</p><h5 style="text-align: center;"><strong><a
title="HTML5 Game Development - Lesson 4 - live demo" href="http://www.script-tutorials.com/demos/186/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="HTML5 Game Development - Lesson 4 - package" href="http://www.script-tutorials.com/demos/186/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Ok, download the example files and lets start coding !</p><hr
/><h3>Step 1. HTML</h3><p>Here are all html of my demo. Then again, if you are still used to the simple html you can check out<br
/> some basic information on html5 <a
href="http://www.webhostingsearch.com/articles/html5-new-placeholder-property-for-better-form-instructions.php">here</a></p><h4>index.html</h4><pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;HTML5 Game Development - Lesson 4 | Script Tutorials&lt;/title&gt;

        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;

        &lt;!--[if lt IE 9]&gt;
          &lt;script src=&quot;http://html5shiv.googlecode.com/svn/trunk/html5.js&quot;&gt;&lt;/script&gt;
        &lt;![endif]--&gt;
        &lt;script src=&quot;http://code.jquery.com/jquery-latest.min.js&quot;&gt;&lt;/script&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/script.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;canvas id=&quot;scene&quot; width=&quot;1000&quot; height=&quot;600&quot;&gt;&lt;/canvas&gt;
        &lt;/div&gt;

        &lt;footer&gt;
            &lt;h2&gt;HTML5 Game Development - Lesson 4&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/html5-game-development-lesson-4/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><h3>Step 2. CSS</h3><p>Here are used CSS styles.</p><h4>css/main.css</h4><p>I will not publish styles today &#8211; this is just page layout styles, nothing special. Available in package.</p><h3>Step 3. JS</h3><h4>js/script.js</h4><pre class="brush:js">
// inner variables
var canvas, ctx;
var backgroundImage;
var iBgShiftX = 100;
var dragon;
var dragonW = 75; // dragon width
var dragonH = 70; // dragon height
var iSprPos = 0; // initial sprite frame
var iSprDir = 4; // initial dragon direction
var dragonSound; // dragon sound
var wingsSound; // wings sound
var bMouseDown = false; // mouse down state
var iLastMouseX = 0;
var iLastMouseY = 0;
// -------------------------------------------------------------

// objects :
function Dragon(x, y, w, h, image) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.image = image;
    this.bDrag = false;
}
// -------------------------------------------------------------

// draw functions :
function clear() { // clear canvas function
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

function drawScene() { // main drawScene function
    clear(); // clear canvas

    // draw background
    iBgShiftX -= 4;
    if (iBgShiftX &lt;= 0) {
        iBgShiftX = 1045;
    }
    ctx.drawImage(backgroundImage, 0 + iBgShiftX, 0, 1000, 940, 0, 0, 1000, 600);

    // update sprite positions
    iSprPos++;
    if (iSprPos &gt;= 9) {
        iSprPos = 0;
    }

    // in case of mouse down - move dragon more close to our mouse
    if (bMouseDown) {
        if (iLastMouseX &gt; dragon.x) {
            dragon.x += 5;
        }
        if (iLastMouseY &gt; dragon.y) {
            dragon.y += 5;
        }
        if (iLastMouseX &lt; dragon.x) {
            dragon.x -= 5;
        }
        if (iLastMouseY &lt; dragon.y) {
            dragon.y -= 5;
        }
    }

    // draw dragon
    ctx.drawImage(dragon.image, iSprPos*dragon.w, iSprDir*dragon.h, dragon.w, dragon.h, dragon.x - dragon.w/2, dragon.y - dragon.h/2, dragon.w, dragon.h);
}

// -------------------------------------------------------------

// initialization
$(function(){
    canvas = document.getElementById('scene');
    ctx = canvas.getContext('2d');

    var width = canvas.width;
    var height = canvas.height;

    // load background image
    backgroundImage = new Image();
    backgroundImage.src = 'images/hell.jpg';
    backgroundImage.onload = function() {
    }
    backgroundImage.onerror = function() {
        console.log('Error loading the background image.');
    }

    // 'Dragon' music init
    dragonSound = new Audio('media/dragon.wav');
    dragonSound.volume = 0.9;

    // 'Wings' music init
    wingsSound = new Audio('media/wings.wav');
    wingsSound.volume = 0.9;
    wingsSound.addEventListener('ended', function() { // looping wings sound
        this.currentTime = 0;
        this.play();
    }, false);
    wingsSound.play();

    // initialization of dragon
    var oDragonImage = new Image();
    oDragonImage.src = 'images/dragon.gif';
    oDragonImage.onload = function() {
    }
    dragon = new Dragon(400, 300, dragonW, dragonH, oDragonImage);

    $('#scene').mousedown(function(e) { // binding mousedown event (for dragging)
        var mouseX = e.layerX || 0;
        var mouseY = e.layerY || 0;
        if(e.originalEvent.layerX) { // changes for jquery 1.7
            mouseX = e.originalEvent.layerX;
            mouseY = e.originalEvent.layerY;
        }

        bMouseDown = true;

        if (mouseX &gt; dragon.x- dragon.w/2 &amp;&amp; mouseX &lt; dragon.x- dragon.w/2 +dragon.w &amp;&amp;
            mouseY &gt; dragon.y- dragon.h/2 &amp;&amp; mouseY &lt; dragon.y-dragon.h/2 +dragon.h) {

            dragon.bDrag = true;
            dragon.x = mouseX;
            dragon.y = mouseY;
        }
    });

    $('#scene').mousemove(function(e) { // binding mousemove event
        var mouseX = e.layerX || 0;
        var mouseY = e.layerY || 0;
        if(e.originalEvent.layerX) { // changes for jquery 1.7
            mouseX = e.originalEvent.layerX;
            mouseY = e.originalEvent.layerY;
        }

        // saving last coordinates
        iLastMouseX = mouseX;
        iLastMouseY = mouseY;

        // perform dragon dragging
        if (dragon.bDrag) {
            dragon.x = mouseX;
            dragon.y = mouseY;
        }

        // change direction of dragon (depends on mouse position)
        if (mouseX &gt; dragon.x &amp;&amp; Math.abs(mouseY-dragon.y) &lt; dragon.w/2) {
            iSprDir = 0;
        } else if (mouseX &lt; dragon.x &amp;&amp; Math.abs(mouseY-dragon.y) &lt; dragon.w/2) {
            iSprDir = 4;
        } else if (mouseY &gt; dragon.y &amp;&amp; Math.abs(mouseX-dragon.x) &lt; dragon.h/2) {
            iSprDir = 2;
        } else if (mouseY &lt; dragon.y &amp;&amp; Math.abs(mouseX-dragon.x) &lt; dragon.h/2) {
            iSprDir = 6;
        } else if (mouseY &lt; dragon.y &amp;&amp; mouseX &lt; dragon.x) {
            iSprDir = 5;
        } else if (mouseY &lt; dragon.y &amp;&amp; mouseX &gt; dragon.x) {
            iSprDir = 7;
        } else if (mouseY &gt; dragon.y &amp;&amp; mouseX &lt; dragon.x) {
            iSprDir = 3;
        } else if (mouseY &gt; dragon.y &amp;&amp; mouseX &gt; dragon.x) {
            iSprDir = 1;
        }
    });

    $('#scene').mouseup(function(e) { // binding mouseup event
        dragon.bDrag = false;
        bMouseDown = false;

        // play dragon sound
        dragonSound.currentTime = 0;
        dragonSound.play();
    });

    setInterval(drawScene, 30); // loop drawScene
});
</pre><p>How it work (shortly): Firstly we define canvas, context, then we load background image, two sounds, then we initialize our dragon and binding different mouse events. In our main loop draw function I am shifting background image (loop), then update sprite positions, and finally &#8211; draw our dragon. In our code you can find several new interesting methods:</p><p>1. Loop background sound</p><pre class="brush:js">
    // 'Wings' music init
    wingsSound = new Audio('media/wings.wav');
    wingsSound.volume = 0.9;
    wingsSound.addEventListener('ended', function() { // looping wings sound
        this.currentTime = 0;
        this.play();
    }, false);
    wingsSound.play();
</pre><p>2. Draw sprites</p><pre class="brush:js">
    var oDragonImage = new Image();
    oDragonImage.src = 'images/dragon.gif';
    oDragonImage.onload = function() {
    }
....
    // update sprite positions
    iSprPos++;
    if (iSprPos &gt;= 9) {
        iSprPos = 0;
    }

    // draw dragon
    ctx.drawImage(dragon.image, iSprPos*dragon.w, iSprDir*dragon.h, dragon.w, dragon.h, dragon.x - dragon.w/2, dragon.y - dragon.h/2, dragon.w, dragon.h);
</pre><p>So, we loading initial image (with set of all sub-images), then &#8211; draw part of that image, then shifting its positions, and draw again (loop).</p><h3>Step 4. Custom files</h3><h4>images/dragon.gif, images/hell.jpg, media/dragon.wav and media/wings.wav</h4><p>All these files available in our package</p><hr
/><h5 style="text-align: center;"><strong><a
title="HTML5 Game Development - Lesson 4 - live demo" href="http://www.script-tutorials.com/demos/186/index.html" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="HTML5 Game Development - Lesson 4 - package" href="http://www.script-tutorials.com/demos/186/source.zip" target="_blank" rel="nofollow">download in package</a></strong></h5><hr
/><h3>Conclusion</h3><p>Are you like our new handy dragon? <img
src='http://www.script-tutorials.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> I will be glad to see your thanks and comments. Good luck!</p><div
class="shr-publisher-1227"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/html5-game-development-navigating-your-spaceship-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/166/thumb.png" alt="HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3" /> <br
/> HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3</a></li><li> <a
href="http://www.script-tutorials.com/html5-game-development-lesson-2/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/157/thumb.png" alt="HTML5 Game Development &#8211; Lesson 2" /> <br
/> HTML5 Game Development &#8211; Lesson 2</a></li><li> <a
href="http://www.script-tutorials.com/html5-game-development-lesson-5/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/205/thumb.png" alt="HTML5 Game Development &#8211; Lesson 5" /> <br
/> HTML5 Game Development &#8211; Lesson 5</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/html5-game-development-lesson-4/feed/</wfw:commentRss> <slash:comments>9</slash:comments> </item> <item><title>Creating an Image Zoomer in HTML5 Canvas</title><link>http://www.script-tutorials.com/html5-canvas-image-zoomer/</link> <comments>http://www.script-tutorials.com/html5-canvas-image-zoomer/#comments</comments> <pubDate>Thu, 20 Oct 2011 17:07:43 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[app]]></category> <category><![CDATA[canvas]]></category> <category><![CDATA[html5]]></category> <category><![CDATA[image]]></category> <category><![CDATA[tutorials]]></category> <category><![CDATA[zoom]]></category> <category><![CDATA[zooming]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1131</guid> <description><![CDATA[HTML5 canvas &#8211; Image zoomer New interesting tutorial &#8211; I will show you how you can create nice and easy Image zoomer using HTML5. Main idea &#8211; to draw a picture on the canvas, add event handlers to mousemove, mousedown and mouseup (to move the enlarged area of ??the motion while holding the mouse). Here [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/html5-image-crop-tool/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/197/thumb.png" alt="HTML5 image crop tool" /> HTML5 image crop tool</a></li><li> <a
href="http://www.script-tutorials.com/html5-canvas-image-effects-app/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/118/thumb.png" alt="Creating an Unbelievable HTML5 Canvas App for Online Image Enhancements" /> Creating an Unbelievable HTML5 Canvas App for Online Image Enhancements</a></li><li> <a
href="http://www.script-tutorials.com/creating-an-html5-canvas-image-color-picker/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/158/thumb.png" alt="Creating an HTML5 Canvas Image Color Picker" /> Creating an HTML5 Canvas Image Color Picker</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="HTML5 canvas - Image zoomer" alt="HTML5 canvas - Image zoomer" src="http://www.script-tutorials.com/demos/167/thumb.png"></div><p><strong>HTML5 canvas &#8211; Image zoomer</strong><br
/> <br
/>New interesting tutorial &#8211; I will show you how you can create nice and easy Image zoomer using HTML5. Main idea &#8211; to draw a picture on the canvas, add event handlers to mousemove, mousedown and mouseup (to move the enlarged area of ??the motion while holding the mouse).<br
/> <span
id="more-1131"></span><br
/></p><p>Here are our demo and downloadable package:</p><h5 style="text-align: center;"><strong><a
title="HTML5 canvas - Image zoomer - demo 167" href="http://www.script-tutorials.com/demos/167/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="HTML5 canvas - Image zoomer - package" href="http://www.script-tutorials.com/demos/167/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Ok, download the source files and lets start coding !</p><hr
/><h3>Step 1. HTML</h3><p>Here are html code of our color picker page</p><h4>index.html</h4><pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;HTML5 canvas - Image zoomer | Script Tutorials&lt;/title&gt;
        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-1.5.2.min.js&quot;&gt;&lt;/script&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/script.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;canvas id=&quot;panel&quot; width=&quot;800&quot; height=&quot;533&quot;&gt;&lt;/canvas&gt;
        &lt;/div&gt;
        &lt;footer&gt;
            &lt;h2&gt;HTML5 canvas - Image zoomer&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/html5-canvas-image-zoomer/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><h3>Step 2. CSS</h3><p>Here are used CSS styles</p><h4>css/main.css</h4><pre class="brush:css">
*{
    margin:0;
    padding:0;
}

body {
    background-color:#bababa;
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}

footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}

footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}

footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}

footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

.container {
    color:#000;
    margin:20px auto;
    position:relative;
    width:800px;
}

#panel {
    border:1px #000 solid;
    box-shadow:4px 6px 6px #444444;
    cursor:crosshair;
}
</pre><h3>Step 3. JS</h3><h4>js/script.js</h4><pre class="brush:js">
// variables
var canvas, ctx;
var image;
var iMouseX, iMouseY = 1;
var bMouseDown = false;
var iZoomRadius = 100;
var iZoomPower = 2;

// drawing functions
function clear() { // clear canvas function
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

function drawScene() { // main drawScene function
    clear(); // clear canvas

    if (bMouseDown) { // drawing zoom area
        ctx.drawImage(image, 0 - iMouseX * (iZoomPower - 1), 0 - iMouseY * (iZoomPower - 1), ctx.canvas.width * iZoomPower, ctx.canvas.height * iZoomPower);
        ctx.globalCompositeOperation = 'destination-atop';

        var oGrd = ctx.createRadialGradient(iMouseX, iMouseY, 0, iMouseX, iMouseY, iZoomRadius);
        oGrd.addColorStop(0.8, &quot;rgba(0, 0, 0, 1.0)&quot;);
        oGrd.addColorStop(1.0, &quot;rgba(0, 0, 0, 0.1)&quot;);
        ctx.fillStyle = oGrd;
        ctx.beginPath();
        ctx.arc(iMouseX, iMouseY, iZoomRadius, 0, Math.PI*2, true);
        ctx.closePath();
        ctx.fill();
    }

    // draw source image
    ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);
}

$(function(){
    // loading source image
    image = new Image();
    image.onload = function () {
    }
    image.src = 'images/image.jpg';

    // creating canvas object
    canvas = document.getElementById('panel');
    ctx = canvas.getContext('2d');

    $('#panel').mousemove(function(e) { // mouse move handler
        var canvasOffset = $(canvas).offset();
        iMouseX = Math.floor(e.pageX - canvasOffset.left);
        iMouseY = Math.floor(e.pageY - canvasOffset.top);
    });

    $('#panel').mousedown(function(e) { // binding mousedown event
        bMouseDown = true;
    });

    $('#panel').mouseup(function(e) { // binding mouseup event
        bMouseDown = false;
    });

    setInterval(drawScene, 30); // loop drawScene
});
</pre><p>What I doing: When we holding the mouse button and start moving it &#8211; variable bMouseDown become three. Then, in the main draw function we just going to check this variable and, in the case of the true, we&#8217;re just going to draw a new additional area with enlarged image (in a circle). After &#8211; pay attention to using of &#8216;globalCompositeOperation&#8217;. Using this method existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content.</p><hr
/><h5 style="text-align: center;"><strong><a
title="HTML5 canvas - Image zoomer - demo 167" href="http://www.script-tutorials.com/demos/167/index.html" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="HTML5 canvas - Image zoomer - package" href="http://www.script-tutorials.com/demos/167/source.zip" target="_blank" rel="nofollow">download in package</a></strong></h5><hr
/><h3>Conclusion</h3><p>Hope that today&#8217;s lesson was interesting for you. In result we got smart and rational solution for zooming of images. Great, isn&#8217;t it? I will be glad to see your thanks and comments. Good luck!</p><div
class="shr-publisher-1131"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/html5-image-crop-tool/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/197/thumb.png" alt="HTML5 image crop tool" /> <br
/> HTML5 image crop tool</a></li><li> <a
href="http://www.script-tutorials.com/html5-canvas-image-effects-app/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/118/thumb.png" alt="Creating an Unbelievable HTML5 Canvas App for Online Image Enhancements" /> <br
/> Creating an Unbelievable HTML5 Canvas App for Online Image Enhancements</a></li><li> <a
href="http://www.script-tutorials.com/creating-an-html5-canvas-image-color-picker/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/158/thumb.png" alt="Creating an HTML5 Canvas Image Color Picker" /> <br
/> Creating an HTML5 Canvas Image Color Picker</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/html5-canvas-image-zoomer/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>HTML5 Game Development &#8211; Navigating Your Spaceship- Lesson 3</title><link>http://www.script-tutorials.com/html5-game-development-navigating-your-spaceship-lesson-3/</link> <comments>http://www.script-tutorials.com/html5-game-development-navigating-your-spaceship-lesson-3/#comments</comments> <pubDate>Wed, 19 Oct 2011 20:19:45 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[coding]]></category> <category><![CDATA[game]]></category> <category><![CDATA[game development]]></category> <category><![CDATA[html5]]></category> <category><![CDATA[tutorial]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1127</guid> <description><![CDATA[HTML5 Game Development &#8211; Lesson 3 Today we continue a series of articles on game development in HTML5 using canvas. Finally, today we will start adding animation, and few more interesting features. Our demonstration will include a spaceship flying through space, and a new element &#8211; the Dialogue. The dialogue will contain two pages, and [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/html5-game-development-lesson-4/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/186/thumb.png" alt="HTML5 Game Development &#8211; Lesson 4" /> HTML5 Game Development &#8211; Lesson 4</a></li><li> <a
href="http://www.script-tutorials.com/html5-game-development-lesson-2/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/157/thumb.png" alt="HTML5 Game Development &#8211; Lesson 2" /> HTML5 Game Development &#8211; Lesson 2</a></li><li> <a
href="http://www.script-tutorials.com/html5-game-development-lesson-1/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/147/thumb.png" alt="Developing Your First HTML5 Game &#8211; Lesson 1" /> Developing Your First HTML5 Game &#8211; Lesson 1</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="HTML5 Game Development - Lesson 3" alt="HTML5 Game Development - Lesson 3" src="http://www.script-tutorials.com/demos/166/thumb.png"></div><p><strong>HTML5 Game Development &#8211; Lesson 3</strong><br
/> <br
/>Today we continue a series of articles on game development in HTML5 using canvas. Finally, today we will start adding animation, and few more interesting features. Our demonstration will include a spaceship flying through space, and a new element &#8211; the Dialogue. The dialogue will contain two pages, and our button will toggle the dialog pages + hide the dialog on the second click.<br
/> <br
/>Our previous article you can read here: <a
href="http://www.script-tutorials.com/html5-game-development-lesson-2/">Developing Your First HTML5 Game – Lesson 2</a>. Our base script will taken from previous letter.<br
/> <span
id="more-1127"></span><br
/></p><p>Here are our demo and downloadable package:</p><h5 style="text-align: center;"><strong><a
title="HTML5 Game Development - Lesson 3 - live demo" href="http://www.script-tutorials.com/demos/166/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="HTML5 Game Development - Lesson 3 - package" href="http://www.script-tutorials.com/demos/166/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Ok, download the example files and lets start coding !</p><hr
/><h3>Step 1. HTML</h3><p>Here are all html of my demo</p><h4>index.html</h4><pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;HTML5 Game Development - Lesson 3 | Script Tutorials&lt;/title&gt;

        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;

        &lt;!--[if lt IE 9]&gt;
          &lt;script src=&quot;http://html5shiv.googlecode.com/svn/trunk/html5.js&quot;&gt;&lt;/script&gt;
        &lt;![endif]--&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-1.5.2.min.js&quot;&gt;&lt;/script&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/script.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;canvas id=&quot;scene&quot; width=&quot;800&quot; height=&quot;600&quot;&gt;&lt;/canvas&gt;
        &lt;/div&gt;

        &lt;footer&gt;
            &lt;h2&gt;HTML5 Game Development - Lesson 3&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/html5-game-development-lesson-3 class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><h3>Step 2. CSS</h3><p>Here are used CSS styles.</p><h4>css/main.css</h4><pre class="brush:css">
/* general styles */
*{
    margin:0;
    padding:0;
}

@font-face {
    font-family: &quot;DS-Digital&quot;;
    src: url(&quot;../fonts/Ds-digib.ttf&quot;);
}

body {
    background-color:#bababa;
    background-image: -webkit-radial-gradient(600px 300px, circle, #ffffff, #bababa 60%);
    background-image: -moz-radial-gradient(600px 300px, circle, #ffffff, #bababa 60%);
    background-image: -o-radial-gradient(600px 300px, circle, #ffffff, #bababa 60%);
    background-image: radial-gradient(600px 300px, circle, #ffffff, #bababa 60%);
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
    min-height:1000px;
}

.container {
    width:100%;
}

.container &gt; * {
    display:block;
    margin:50px auto;
}

footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}

footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}

footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}

footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

h3 {
    text-align:center;
}

#scene {
    position:relative;
}
</pre><p>Pay attention to &#8216;@font-face&#8217;. We will using this way to link custom font file (ttf) to our lesson (to draw at canvas).</p><h3>Step 3. JS</h3><h4>js/jquery-1.5.2.min.js</h4><p>We will using jQuery for our demo. This allows easy bind different events (for mouse etc). Next file most important (here are all our html5 functional):</p><h4>js/script.js</h4><pre class="brush:js">
// inner variables
var canvas, ctx;
var button;
var backgroundImage;
var spaceShip;
var iBgShiftX = 1024;
var bDrawDialog = true;
var iDialogPage = 1;
// -------------------------------------------------------------

// objects :
function Button(x, y, w, h, state, image) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.state = state;
    this.imageShift = 0;
    this.image = image;
}
function SpaceShip(x, y, w, h, image) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.image = image;
    this.bDrag = false;
}
// -------------------------------------------------------------

// draw functions :

function clear() { // clear canvas function
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

function drawDialog() { // draw dialog function
    if (bDrawDialog) {
        var bg_gradient = ctx.createLinearGradient(0, 200, 0, 400);
        bg_gradient.addColorStop(0.0, 'rgba(160, 160, 160, 0.8)');
        bg_gradient.addColorStop(1.0, 'rgba(250, 250, 250, 0.8)');

        ctx.beginPath(); // custom shape begin
        ctx.fillStyle = bg_gradient;
        ctx.moveTo(100, 100);
        ctx.lineTo(700, 100);
        ctx.lineTo(700, 500);
        ctx.lineTo(100, 500);
        ctx.lineTo(100, 100);
        ctx.closePath(); // custom shape end
        ctx.fill(); // fill custom shape

        ctx.lineWidth = 2;
        ctx.strokeStyle = 'rgba(128, 128, 128, 0.5)';
        ctx.stroke(); // draw border

        // draw the title text
        ctx.font = '42px DS-Digital';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'top';
        ctx.shadowColor = '#000';
        ctx.shadowOffsetX = 2;
        ctx.shadowOffsetY = 2;
        ctx.shadowBlur = 2;
        ctx.fillStyle = '#fff';
        if (iDialogPage == 1) {
            ctx.fillText('Welcome to lesson #3', ctx.canvas.width/2, 150);
            ctx.font = '24px DS-Digital';
            ctx.fillText('After closing dialog you will able', ctx.canvas.width/2, 250);
            ctx.fillText('to handle with spaceship with your mouse', ctx.canvas.width/2, 280);
        } else if (iDialogPage == 2) {
            ctx.fillText('Second page of dialog', ctx.canvas.width/2, 150);
            ctx.font = '24px DS-Digital';
            ctx.fillText('Any another text', ctx.canvas.width/2, 250);
        }
    }
}

function drawScene() { // main drawScene function
    clear(); // clear canvas

    // draw background
    iBgShiftX -= 10;
    if (iBgShiftX &lt;= 0) {
        iBgShiftX = 1024;
    }
    ctx.drawImage(backgroundImage, 0 + iBgShiftX, 0, 1024, 768, 0, 0, 800, 600);

    // draw space ship
    ctx.drawImage(spaceShip.image, 0, 0, spaceShip.w, spaceShip.h, spaceShip.x-128, spaceShip.y-128, spaceShip.w, spaceShip.h);

    // draw dialog
    drawDialog();

    // draw button
    ctx.drawImage(button.image, 0, button.imageShift, button.w, button.h, button.x, button.y, button.w, button.h);

    // draw button's text
    ctx.font = '22px DS-Digital';
    ctx.fillStyle = '#ffffff';
    ctx.fillText('next/hide/show', 400, 465);
    ctx.fillText('dialog', 400, 500);
}

// -------------------------------------------------------------

// initialization
$(function(){
    canvas = document.getElementById('scene');
    ctx = canvas.getContext('2d');

    var width = canvas.width;
    var height = canvas.height;

    // load background image
    backgroundImage = new Image();
    backgroundImage.src = 'images/stars.jpg';
    backgroundImage.onload = function() {
    }
    backgroundImage.onerror = function() {
        console.log('Error loading the background image.');
    }

    // initialization of space ship
    var oSpShipImage = new Image();
    oSpShipImage.src = 'images/space_ship.png';
    oSpShipImage.onload = function() {
    }
    spaceShip = new SpaceShip(400, 300, 256, 256, oSpShipImage);

    // load the button sprite image
    var buttonImage = new Image();
    buttonImage.src = 'images/button.png';
    buttonImage.onload = function() {
    }
    button = new Button(310, 450, 180, 120, 'normal', buttonImage);

    $('#scene').mousedown(function(e) { // binding mousedown event (for dragging)

        var mouseX = e.layerX || 0;
        var mouseY = e.layerY || 0;

        if (!bDrawDialog &amp;&amp;
            mouseX &gt; spaceShip.x-128 &amp;&amp; mouseX &lt; spaceShip.x-128+spaceShip.w &amp;&amp;
            mouseY &gt; spaceShip.y-128 &amp;&amp; mouseY &lt; spaceShip.y-128+spaceShip.h) {

            spaceShip.bDrag = true;
            spaceShip.x = mouseX;
            spaceShip.y = mouseY;
        }

        // button behavior
        if (mouseX &gt; button.x &amp;&amp; mouseX &lt; button.x+button.w &amp;&amp; mouseY &gt; button.y &amp;&amp; mouseY &lt; button.y+button.h) {
            button.state = 'pressed';
            button.imageShift = 262;
        }
    });

    $('#scene').mousemove(function(e) { // binding mousemove event
        var mouseX = e.layerX || 0;
        var mouseY = e.layerY || 0;

        if (!bDrawDialog &amp;&amp; spaceShip.bDrag) {
            spaceShip.x = mouseX;
            spaceShip.y = mouseY;
        }

        // button behavior
        if (button.state != 'pressed') {
            button.state = 'normal';
            button.imageShift = 0;
            if (mouseX &gt; button.x &amp;&amp; mouseX &lt; button.x+button.w &amp;&amp; mouseY &gt; button.y &amp;&amp; mouseY &lt; button.y+button.h) {
                button.state = 'hover';
                button.imageShift = 131;
            }
        }
    });

    $('#scene').mouseup(function(e) { // binding mouseup event
        spaceShip.bDrag = false;

        // button behavior
        if (button.state == 'pressed') {
            if (iDialogPage == 0) {
                iDialogPage++;
                bDrawDialog = !bDrawDialog;
            } else if (iDialogPage == 2) {
                iDialogPage = 0;
                bDrawDialog = !bDrawDialog;
            } else {
                iDialogPage++;
            }
        }
        button.state = 'normal';
        button.imageShift = 0;
    });

    setInterval(drawScene, 30); // loop drawScene
});
</pre><p>Here are several explanations about new features. 1. Drawing animated space with stars (pretty easy &#8211; we will shift image coordinates):</p><pre class="brush:js">
    iBgShiftX -= 10;
    if (iBgShiftX &lt;= 0) {
        iBgShiftX = 1024;
    }
    ctx.drawImage(backgroundImage, 0 + iBgShiftX, 0, 1024, 768, 0, 0, 800, 600);
</pre><p>Hope that all rest code pretty understandable. I added comments quite anywhere.</p><h3>Step 4. Custom files</h3><h4>fonts/Ds-digib.ttf, images/button.png, images/space_ship.png and images/stars.jpg</h4><p>All these files will available in our package</p><hr
/><h5 style="text-align: center;"><strong><a
title="HTML5 Game Development - Lesson 3 - live demo" href="http://www.script-tutorials.com/demos/166/index.html" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="HTML5 Game Development - Lesson 3 - package" href="http://www.script-tutorials.com/demos/166/source.zip" target="_blank" rel="nofollow">download in package</a></strong></h5><hr
/><p>Separate big thanks to <a
href="http://www.packtpub.com/html5-games-development-using-css-javascript-beginners-guide/book">this book</a>. This tell us about development of games in HTML5. Now it&#8217;s one of my favorite books <img
src='http://www.script-tutorials.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /></p><p><img
src="https://www.packtpub.com/sites/default/files/imagecache/productview/1260OT_HTML5 Game Development Beginner's Guide_cov.jpg" alt="HTML5 Games Development by Example: Beginner's Guide" /></p><hr
/><h3>Conclusion</h3><p>Are you like our new spaceship? <img
src='http://www.script-tutorials.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> I will be glad to see your thanks and comments. Good luck!</p><div
class="shr-publisher-1127"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/html5-game-development-lesson-4/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/186/thumb.png" alt="HTML5 Game Development &#8211; Lesson 4" /> <br
/> HTML5 Game Development &#8211; Lesson 4</a></li><li> <a
href="http://www.script-tutorials.com/html5-game-development-lesson-2/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/157/thumb.png" alt="HTML5 Game Development &#8211; Lesson 2" /> <br
/> HTML5 Game Development &#8211; Lesson 2</a></li><li> <a
href="http://www.script-tutorials.com/html5-game-development-lesson-1/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/147/thumb.png" alt="Developing Your First HTML5 Game &#8211; Lesson 1" /> <br
/> Developing Your First HTML5 Game &#8211; Lesson 1</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/html5-game-development-navigating-your-spaceship-lesson-3/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Creating a Photo Array in WebGL</title><link>http://www.script-tutorials.com/creating-photo-array-in-webgl/</link> <comments>http://www.script-tutorials.com/creating-photo-array-in-webgl/#comments</comments> <pubDate>Tue, 18 Oct 2011 17:19:10 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[array]]></category> <category><![CDATA[html5]]></category> <category><![CDATA[photo]]></category> <category><![CDATA[slides]]></category> <category><![CDATA[webgl]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1122</guid> <description><![CDATA[Creating photo array in WebGL Today we continue HTML5 WebGL examples. I prepared a nice photo gallery for you. Images in this gallery will be replaced by a mouse click. Here are our demo and downloadable package: Live Demo download in package Ok, download the example files and lets start coding ! Step 1. HTML [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/webgl-box-photo-slideshow/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/174/thumb.png" alt="Creating a 3D Animated Box HTML5 WebGL Photo Slideshow" /> Creating a 3D Animated Box HTML5 WebGL Photo Slideshow</a></li><li> <a
href="http://www.script-tutorials.com/twisting-images-webgl/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/144/thumb.png" alt="Creating a Keyboard Sensitive 3D Twisted Images in WebGl" /> Creating a Keyboard Sensitive 3D Twisted Images in WebGl</a></li><li> <a
href="http://www.script-tutorials.com/making-3d-webgl-demonstration/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/139/thumb.png" alt="Creating an Animated 3D WebGL Demonstration" /> Creating an Animated 3D WebGL Demonstration</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Creating photo array in WebGL" alt="Creating photo array in WebGL" src="http://www.script-tutorials.com/demos/165/thumb.png"></div><p><strong>Creating photo array in WebGL</strong><br
/> <br
/>Today we continue HTML5 WebGL examples. I prepared a nice photo gallery for you. Images in this gallery will be replaced by a mouse click.<br
/> <span
id="more-1122"></span></p><p>Here are our demo and downloadable package:</p><h5 style="text-align: center;"><strong><a
title="Creating photo array in WebGL - demo 165" href="http://www.script-tutorials.com/demos/165/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Creating photo array in WebGL - demo 165" href="http://www.script-tutorials.com/demos/165/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Ok, download the example files and lets start coding !</p><hr
/><h3>Step 1. HTML</h3><p>Here are html sources of our demo. As you can see &#8211; just empty page.</p><h4>index.html</h4><pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;Creating photo array in WebGL | Script Tutorials&lt;/title&gt;
        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/glMatrix-0.9.5.min.js&quot;&gt;&lt;/script&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/webgl-utils.js&quot;&gt;&lt;/script&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/script.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body onload=&quot;initWebGl();&quot;&gt;
        &lt;div class=&quot;container&quot; id=&quot;container&quot;&gt;
            &lt;h3&gt;You can use your mouse to switch images&lt;/h3&gt;
            &lt;canvas id=&quot;panel&quot; width=&quot;800&quot; height=&quot;600&quot;&gt;&lt;/canvas&gt;
        &lt;/div&gt;

        &lt;footer&gt;
            &lt;h2&gt;Creating photo array in WebGL&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/creating-photo-array-in-webgl/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><h3>Step 2. CSS</h3><p>Here are used CSS styles.</p><h4>css/main.css</h4><pre class="brush:css">
*{
    margin:0;
    padding:0;
}

body {
    /*background-color:#bababa;*/
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}

footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}

footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}

footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}

footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

.container {
    margin:20px auto;
    position:relative;
    width:800px;
}

#panel {
    cursor:pointer;
}
</pre><h3>Step 3. JS</h3><h4>js/webgl-utils.js and js/glMatrix-0.9.5.min.js</h4><p>These files we will use in project for working with WebGL. Both files will in our package.</p><h4>js/script.js</h4><pre class="brush:js">
var gl; // global WebGL object
var shaderProgram;

var pics_names=['1.png', '2.png', '3.png', '4.png', '5.png', '6.png', '7.png'];
var pics_num=pics_names.length;

// diffirent initializations

function initGL(canvas) {
    try {
        gl = canvas.getContext('experimental-webgl');
        gl.viewportWidth = canvas.width;
        gl.viewportHeight = canvas.height;
    } catch (e) {}
    if (! gl) {
        alert('Can`t initialise WebGL, not supported');
    }
}

function getShader(gl, type) {
    var str = '';
    var shader;

    if (type == 'x-fragment') {
        str = &quot;#ifdef GL_ES\n&quot;+
&quot;precision highp float;\n&quot;+
&quot;#endif\n&quot;+
&quot;varying vec2 vTextureCoord;\n&quot;+
&quot;uniform sampler2D uSampler;\n&quot;+
&quot;void main(void) {\n&quot;+
&quot;    gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));\n&quot;+
&quot;}\n&quot;;
        shader = gl.createShader(gl.FRAGMENT_SHADER);
    } else if (type == 'x-vertex') {
        str = &quot;attribute vec3 aVertexPosition;\n&quot;+
&quot;attribute vec2 aTextureCoord;\n&quot;+
&quot;uniform mat4 uMVMatrix;\n&quot;+
&quot;uniform mat4 uPMatrix;\n&quot;+
&quot;varying vec2 vTextureCoord;\n&quot;+
&quot;void main(void) {\n&quot;+
&quot;    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n&quot;+
&quot;    vTextureCoord = aTextureCoord;\n&quot;+
&quot;}\n&quot;;
        shader = gl.createShader(gl.VERTEX_SHADER);
    } else {
        return null;
    }

    gl.shaderSource(shader, str);
    gl.compileShader(shader);

    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        alert(gl.getShaderInfoLog(shader));
        return null;
    }
    return shader;
}

function initShaders() {
    var fragmentShader = getShader(gl, 'x-fragment');
    var vertexShader = getShader(gl, 'x-vertex');

    shaderProgram = gl.createProgram();
    gl.attachShader(shaderProgram, vertexShader);
    gl.attachShader(shaderProgram, fragmentShader);
    gl.linkProgram(shaderProgram);

    if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
        alert('Can`t initialise shaders');
    }

    gl.useProgram(shaderProgram);

    shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, 'aVertexPosition');
    gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

    shaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, 'aTextureCoord');
    gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);

    shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, 'uPMatrix');
    shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, 'uMVMatrix');
    shaderProgram.samplerUniform = gl.getUniformLocation(shaderProgram, 'uSampler');
}

var objVertexPositionBuffer=new Array();
var objVertexTextureCoordBuffer=new Array();
var objVertexIndexBuffer=new Array();

function initObjBuffers() {
    for (var i=0;i&lt;pics_num;i=i+1) {
        objVertexPositionBuffer[i] = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, objVertexPositionBuffer[i]);
        vertices = [
            -0.5, -0.5, -i * 2,
            -0.5,  0.5, -i * 2,
             0.5,  0.5, -i * 2,
             0.5, -0.5, -i * 2,
        ];
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
        objVertexPositionBuffer[i].itemSize = 3;
        objVertexPositionBuffer[i].numItems = 4;

        objVertexTextureCoordBuffer[i] = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER,  objVertexTextureCoordBuffer[i] );
        var textureCoords = [
            0.0, 0.0,
            0.0, 1.0,
            1.0, 1.0,
            1.0, 0.0,
        ];
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoords), gl.STATIC_DRAW);
        objVertexTextureCoordBuffer[i].itemSize = 2;
        objVertexTextureCoordBuffer[i].numItems = 4;

        objVertexIndexBuffer[i] = gl.createBuffer();
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, objVertexIndexBuffer[i]);
        var objVertexIndices = [
            0, 1, 2,
            0, 2, 3,
        ];
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(objVertexIndices), gl.STATIC_DRAW);
        objVertexIndexBuffer[i].itemSize = 1;
        objVertexIndexBuffer[i].numItems = 6;
    }
}

function handleLoadedTexture(texture) {
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.image);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    gl.bindTexture(gl.TEXTURE_2D, null);
}

var aTextures = Array();
function initTexture(image) {
    var crateImage = new Image();

    var texture = gl.createTexture();
    texture.image = crateImage;
    crateImage.src = image;

    crateImage.onload = function () {
        handleLoadedTexture(texture)
    }
    return texture;
}

function initTextures() {
    for (var i=0; i &lt; pics_num; i++) {
        aTextures[i]=initTexture(pics_names[i]);
    }
}

var mvMatrix = mat4.create();
var mvMatrixStack = [];
var pMatrix = mat4.create();

function setMatrixUniforms() {
    gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
    gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
}

// variables
var z = -2.5;
var iImg = 1;
var bMove = false;
var iTimer = 0;
var iStep = 0.03;

// mouse handler
function handleMouseDown(event) {
    if (bMove == false &amp;&amp; iTimer == 0) {
        bMove = true;
        iTimer = 2;
        iImg++;
    }
}

// Draw scene and initialization

var MoveMatrix = mat4.create();
mat4.identity(MoveMatrix);

function drawScene() {
    gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    mat4.perspective(30, gl.viewportWidth / gl.viewportHeight, 2.0, 100.0, pMatrix);

    mat4.identity(mvMatrix);

    mat4.translate(mvMatrix, [0.0, 0.0, z]);

    mat4.multiply(mvMatrix, MoveMatrix);

    for (var i=0;i&lt;pics_num;i=i+1) {
        gl.bindBuffer(gl.ARRAY_BUFFER, objVertexPositionBuffer[i]);
        gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, objVertexPositionBuffer[i].itemSize, gl.FLOAT, false, 0, 0);

        gl.bindBuffer(gl.ARRAY_BUFFER, objVertexTextureCoordBuffer[i]);
        gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, objVertexTextureCoordBuffer[i].itemSize, gl.FLOAT, false, 0, 0);

        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, aTextures[i]);
        gl.uniform1i(shaderProgram.samplerUniform, 0);

        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, objVertexIndexBuffer[i]);
        setMatrixUniforms();
        gl.drawElements(gl.TRIANGLES, objVertexIndexBuffer[i].numItems, gl.UNSIGNED_SHORT, 0);
    }
}

var lastTime = 0;
function animate() {
    var timeNow = new Date().getTime();
    if (lastTime != 0) {

        if (z &gt; (pics_num - 2) * 2) {
            z = -4.0;
            iImg = 1;
        }

        if (bMove == true &amp;&amp; iTimer &gt; 0) {
            iTimer -= iStep;
            z += iStep;

            if (iTimer &lt;= 0) {
                bMove = false;
                iTimer = 0;
            }
        }
    }
    lastTime = timeNow;
}

function drawFrame() {
    requestAnimFrame(drawFrame);
    drawScene();
    animate();
}

function initWebGl() {
    var canvas = document.getElementById('panel');
    initGL(canvas);
    initShaders();
    initObjBuffers();
    initTextures();

    gl.clearColor(1.0, 1.0, 1.0, 1.0);
    gl.enable(gl.DEPTH_TEST);

    canvas.onmousedown = handleMouseDown;

    drawFrame();
}
</pre><p>This is pretty long code, but it is most important. I separated all code to 3 sides: initializations, handlers and drawing of scene. Hope that you already read our previos post where I told about creating another <a
href="http://www.script-tutorials.com/twisting-images-webgl/">photo gallery with WebGL</a>. In this case it will more easy to understand today&#8217;s code. Today we handle click events for other purposes. We&#8217;ll run some internal timer &#8211; and will change the Z coordinate on the timer (in the end &#8211; the pictures are moving forward, and then disappear).</p><h3>Step 4. Images</h3><p>All these images we will using for twisting:</p><pre class="sources">
    <img src="http://www.script-tutorials.com/demos/165/1.png" alt="1" />
    <img src="http://www.script-tutorials.com/demos/165/2.png" alt="2" />
    <img src="http://www.script-tutorials.com/demos/165/3.png" alt="3" />
    <img src="http://www.script-tutorials.com/demos/165/4.png" alt="4" />
    <img src="http://www.script-tutorials.com/demos/165/5.png" alt="5" />
    <img src="http://www.script-tutorials.com/demos/165/6.png" alt="6" />
    <img src="http://www.script-tutorials.com/demos/165/7.png" alt="7" />
</pre><hr
/><h5 style="text-align: center;"><strong><a
title="Creating photo array in WebGL - demo 165" href="http://www.script-tutorials.com/demos/165/index.html" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Creating photo array in WebGL - demo 165" href="http://www.script-tutorials.com/demos/165/source.zip" target="_blank" rel="nofollow">download in package</a></strong></h5><hr
/><h3>Conclusion</h3><p>I hope you enjoyed today`s result. If you have any suggestions or ideas &#8211; share it <img
src='http://www.script-tutorials.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> Welcome back our friends!</p><div
class="shr-publisher-1122"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/webgl-box-photo-slideshow/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/174/thumb.png" alt="Creating a 3D Animated Box HTML5 WebGL Photo Slideshow" /> <br
/> Creating a 3D Animated Box HTML5 WebGL Photo Slideshow</a></li><li> <a
href="http://www.script-tutorials.com/twisting-images-webgl/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/144/thumb.png" alt="Creating a Keyboard Sensitive 3D Twisted Images in WebGl" /> <br
/> Creating a Keyboard Sensitive 3D Twisted Images in WebGl</a></li><li> <a
href="http://www.script-tutorials.com/making-3d-webgl-demonstration/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/139/thumb.png" alt="Creating an Animated 3D WebGL Demonstration" /> <br
/> Creating an Animated 3D WebGL Demonstration</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/creating-photo-array-in-webgl/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Creating HTML5 Image Effects App &#8211; Adding Horizontal Flip</title><link>http://www.script-tutorials.com/html5-image-effects-app-adding-horizontal-flip/</link> <comments>http://www.script-tutorials.com/html5-image-effects-app-adding-horizontal-flip/#comments</comments> <pubDate>Mon, 26 Sep 2011 15:37:52 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[application]]></category> <category><![CDATA[effects]]></category> <category><![CDATA[horizontal flip]]></category> <category><![CDATA[html5]]></category> <category><![CDATA[image]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1044</guid> <description><![CDATA[HTML5 Image Effects App &#8211; Adding Horizontal Flip Today we going to continue HTML5 canvas examples, I hope you enjoy this series of articles. Even for me, working with graphics, images brings pleasure. Sure that you like this too. Today we will be adding new filter &#8211; Horizontal Flip. Here are our demo and downloadable [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/html5-canvas-image-effects-app-adding-blur/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/127/thumb.png" alt="HTML5 Canvas Image Effects App &#8211; Adding Blur" /> HTML5 Canvas Image Effects App &#8211; Adding Blur</a></li><li> <a
href="http://www.script-tutorials.com/html5-image-effects-app-adding-noise-and-invert/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/138/thumb.png" alt="HTML5 Image Effects App &#8211; Adding Noise and Invert" /> HTML5 Image Effects App &#8211; Adding Noise and Invert</a></li><li> <a
href="http://www.script-tutorials.com/html5-canvas-image-effects-app/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/118/thumb.png" alt="Creating an Unbelievable HTML5 Canvas App for Online Image Enhancements" /> Creating an Unbelievable HTML5 Canvas App for Online Image Enhancements</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="HTML5 Image Effects App - Adding Horizontal Flip" alt="HTML5 Image Effects App - Adding Horizontal Flip" src="http://www.script-tutorials.com/demos/149/thumb.png"></div><p><strong>HTML5 Image Effects App &#8211; Adding Horizontal Flip</strong><br
/> <br
/>Today we going to continue HTML5 canvas examples, I hope you enjoy this series of articles. Even for me, working with graphics, images brings pleasure. Sure that you like this too. Today we will be adding new filter &#8211; Horizontal Flip.<br
/> <span
id="more-1044"></span><br
/></p><p>Here are our demo and downloadable package:</p><h5 style="text-align: center;"><strong><a
title="HTML5 Image Effects App - Adding Horizontal Flip - demo 149" href="http://www.script-tutorials.com/demos/149/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="HTML5 Image Effects App - Adding Horizontal Flip - demo 149" href="http://www.script-tutorials.com/demos/149/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Ok, download the example files and lets start coding !</p><hr
/><h3>Step 1. HTML</h3><p>Here are all html of my demo</p><h4>index.html</h4><pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;HTML5 Image Effects App - Adding Horizontal Flip | Script Tutorials&lt;/title&gt;

        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/script.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class=&quot;container&quot;&gt;

            &lt;div class=&quot;column1&quot;&gt;
                Reset to:&lt;br /&gt;
                &lt;input type=&quot;button&quot; onclick=&quot;resetToColor()&quot; value=&quot;Color&quot; /&gt;
                &lt;input type=&quot;button&quot; onclick=&quot;resetToGrayscale()&quot; value=&quot;Grayscale&quot; /&gt;&lt;hr /&gt;
                Effects:&lt;br /&gt;
                &lt;input type=&quot;button&quot; onclick=&quot;resetToBlur()&quot; value=&quot;1. Blur&quot; /&gt;&lt;br /&gt;
                &lt;input type=&quot;button&quot; onclick=&quot;resetToNoise()&quot; value=&quot;2. Add noise&quot; /&gt;&lt;br /&gt;
                &lt;input type=&quot;button&quot; onclick=&quot;resetToInvert()&quot; value=&quot;3. Invert colors&quot; /&gt;
                &lt;input type=&quot;button&quot; onclick=&quot;resetToFlopHor()&quot; value=&quot;4. Horizontal Flip&quot; /&gt;&lt;hr /&gt;
                Adjustment:&lt;br /&gt;
                &lt;input type=&quot;button&quot; onclick=&quot;changeGrayValue(0.1)&quot; value=&quot;Lighter&quot; /&gt;&lt;br /&gt;
                &lt;input type=&quot;button&quot; onclick=&quot;changeGrayValue(-0.1)&quot; value=&quot;Darker&quot; /&gt;&lt;br /&gt;
                Red: &lt;input type=&quot;button&quot; onclick=&quot;changeColorValue('er', 10)&quot; value=&quot;More&quot; /&gt;
                &lt;input type=&quot;button&quot; onclick=&quot;changeColorValue('er', -10)&quot; value=&quot;Less&quot; /&gt;&lt;br /&gt;
                Green: &lt;input type=&quot;button&quot; onclick=&quot;changeColorValue('eg', 10)&quot; value=&quot;More&quot; /&gt;
                &lt;input type=&quot;button&quot; onclick=&quot;changeColorValue('eg', -10)&quot; value=&quot;Less&quot; /&gt;&lt;br /&gt;
                Blue: &lt;input type=&quot;button&quot; onclick=&quot;changeColorValue('eb', 10)&quot; value=&quot;More&quot; /&gt;
                &lt;input type=&quot;button&quot; onclick=&quot;changeColorValue('eb', -10)&quot; value=&quot;Less&quot; /&gt;
                Blur: &lt;input type=&quot;button&quot; onclick=&quot;changeBlurValue(1)&quot; value=&quot;More&quot; /&gt;
                &lt;input type=&quot;button&quot; onclick=&quot;changeBlurValue(-1)&quot; value=&quot;Less&quot; /&gt;&lt;br /&gt;
            &lt;/div&gt;
            &lt;div class=&quot;column2&quot;&gt;
                &lt;canvas id=&quot;orig&quot; width=&quot;500&quot; height=&quot;333&quot;&gt;&lt;/canvas&gt;
                &lt;canvas id=&quot;panel&quot; width=&quot;500&quot; height=&quot;333&quot;&gt;&lt;/canvas&gt;
            &lt;/div&gt;
            &lt;div style=&quot;clear:both;&quot;&gt;&lt;/div&gt;
        &lt;/div&gt;

        &lt;footer&gt;
            &lt;h2&gt;HTML5 Image Effects App - Adding Horizontal Flip&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/html5-image-effects-app-adding-horizontal-flip&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><p>What I did since <a
href="http://www.script-tutorials.com/html5-image-effects-app-adding-noise-and-invert/">last our version</a>: changed main layout a little and add new button for new Horizontal Flip.</p><h3>Step 2. CSS</h3><p>Here are used CSS styles.</p><h4>css/main.css</h4><pre class="brush:css">
/* general styles */
*{
    margin:0;
    padding:0;
}

body {
    background-color:#bababa;
    background-image: -webkit-radial-gradient(600px 200px, circle, #ffffff, #bababa 50%);
    background-image: -moz-radial-gradient(600px 200px, circle, #ffffff, #bababa 50%);
    background-image: -o-radial-gradient(600px 200px, circle, #ffffff, #bababa 50%);
    background-image: radial-gradient(600px 200px, circle, #ffffff, #bababa 50%);
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}

footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}

footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}

footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}

footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

/* tutorial styles */
.container {
    color:#000;
    margin:20px auto;
    position:relative;
    width:730px;
}
.column1 {
    float:left;
    padding-right:10px;
    text-align:right;
    width:185px;
}
.column2 {
    float:left;
    width:500px;
    background-color:#888;
    padding:10px;
}
input[type=button] {
    margin:5px;
}
</pre><h3>Step 3. JS</h3><p>As I mentioned in previous article &#8211; don`t need to publish whole code here again and again &#8211; we will publish only new functions. Here are new function for Horizontal Flip:</p><h4>js/script.js</h4><pre class="brush:js">
function FlipHor() {
    func = 'flip_hor'; // last used function
    var imgd = context.getImageData(0, 0, iW, iH);
    var data = imgd.data;

    var imgd2 = context.getImageData(0, 0, iW, iH);
    var data2 = imgd2.data;

    for (var x = 0; x &lt; iW/2; x++) {
        for (var y = 0; y &lt; iH; y++) {

            var i = (y*iW + x);
            var i2 = (y*iW + ((iW-1)-x));

            var iP1 = data2[i*4]*p1+er;
            var iP2 = data2[i*4+1]*p2+eg;
            var iP3 = data2[i*4+2]*p3+eb;

            data[i*4]   = data[i2*4]*p1+er; // red
            data[i*4+1] = data[i2*4+1]*p2+eg; // green
            data[i*4+2] = data[i2*4+2]*p3+eb; // blue

            data[i2*4]   = iP1; // red
            data[i2*4+1] = iP2; // green
            data[i2*4+2] = iP3; // blue
        }
    }

    context.putImageData(imgd, 0, 0);
}
</pre><hr
/><h5 style="text-align: center;"><strong><a
title="HTML5 Image Effects App - Adding Horizontal Flip - demo 149" href="http://www.script-tutorials.com/demos/149/index.html" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="HTML5 Image Effects App - Adding Horizontal Flip - demo 149" href="http://www.script-tutorials.com/demos/149/source.zip" target="_blank" rel="nofollow">download in package</a></strong></h5><hr
/><h3>Conclusion</h3><p>Hope that today`s lesson was interesting for you. We added new effect to our application &#8211; Horizontal Flip. I will be glad to see your thanks and comments. Good luck!</p><div
class="shr-publisher-1044"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/html5-canvas-image-effects-app-adding-blur/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/127/thumb.png" alt="HTML5 Canvas Image Effects App &#8211; Adding Blur" /> <br
/> HTML5 Canvas Image Effects App &#8211; Adding Blur</a></li><li> <a
href="http://www.script-tutorials.com/html5-image-effects-app-adding-noise-and-invert/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/138/thumb.png" alt="HTML5 Image Effects App &#8211; Adding Noise and Invert" /> <br
/> HTML5 Image Effects App &#8211; Adding Noise and Invert</a></li><li> <a
href="http://www.script-tutorials.com/html5-canvas-image-effects-app/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/118/thumb.png" alt="Creating an Unbelievable HTML5 Canvas App for Online Image Enhancements" /> <br
/> Creating an Unbelievable HTML5 Canvas App for Online Image Enhancements</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/html5-image-effects-app-adding-horizontal-flip/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: basic (User agent is rejected)
Database Caching using disk: basic

Served from: www.script-tutorials.com @ 2012-02-04 21:55:57 -->
