• HTML/CSS
  • jQuery
  • PHP
  • JS
  • AJAX
  • MySQL
  • Res
  • XSLT
  • Contact Us
  • HTML/CSS
    • Game Development →
      • HTML5 Game Development - Lesson 1
      • HTML5 Game Development - Lesson 2
      • HTML5 Game Development - Lesson 3
      • HTML5 Game Development - Lesson 4
      • HTML5 Game Development - Lesson 5
      • HTML5 Game Development - Lesson 6
      • HTML5 Game Development - Lesson 7
    • Menus →
      • CSS3 multilevel menu with transition and animation
      • Marble Style CSS3 Navigation Menu
      • Toggle CSS3 Bottom Navigation Bar
      • Accordian like CSS3 Onclick Vertical Navigation
      • Multilevel CSS3 Metal Navigation with icons
      • Click-action CSS3 Dropdown Menu with jQuery
      • Click action Multi-level CSS3 Dropdown Menu
      • CSS3 Animated Menu
      • CSS3/jQuery crossbrowser Drop-down menu with tabs
      • CSS3 Drop sliding list Menu #6
      • CSS3 Slideout Menu #5
      • CSS3 Dropdown Menu #4
      • CSS3 Dropdown Menu #3
      • CSS3 Dropdown Menu #2
      • Cool CSS3 Dropdown Menu
    • Templates →
      • Robo Splash Page Layout
      • 'Mono' HTML5 CSS3 Single Page Layout
      • HTML5/CSS3 single page layout - Art theme
      • Attractive HTML CSS Anime Theme Website Layout
      • HTML CSS website layout #4 - Gray theme
      • Dark and clean HTML CSS website layout
      • HTML5&CSS3 single page layout - Rock portal
      • E-Store HTML5 CSS3 Single Page Layout
      • Under Water Themed HTML5 & CSS3 single page Layout
      • HTML5 & CSS3 Single Page Web Layout
    • HTML5 tutorials →
      • HTML5 Canvas Slideshow
      • HTML5 canvas - Custom brush #2 (Bubble brush)
      • HTML5 canvas - Custom brush (BezierCurveBrush)
      • HTML5 Face Builder
      • Pure HTML5 file upload
      • HTML5 image crop tool
      • HTML5 animation - patterns with loops
      • HTML5 3D circle text with shadows
      • HTML5 canvas pixelate effect
      • Animated Moving Clouds using HTML5
      • Animated Fireplace in HTML5
      • 3D Animated Box HTML5 WebGL Photo Slideshow
      • Your Own Paint Program
      • Image Zoomer in HTML5 Canvas
      • Photo Array in WebGL
      • HTML5 Canvas Image Color Picker
      • HTML5 Image Effects App - Adding Horizontal Flip
      • Keyboard Sensitive 3D Twisted Images in WebGl
      • Animated 3D WebGL Demonstration
      • HTML5 Image Effects App - Adding Noise and Invert
      • HTML5 Canvas Image Effects App - Adding Blur
      • Attractive Presentation with HTML5
      • HTML5 Canvas App for Online Image Enhancements
      • Water Ripple effect using HTML5 canvas
      • Animated 3D canvas object in HTML5
    • CSS3 tutorials →
      • CSS3 Image Hover Effects
      • CSS3 Modal Popups
      • Isometric interactive interior guide
      • Analog Clock with Pure CSS3
      • CSS3 Optical Illusions
      • CSS3 Animated Photo Slider
      • CSS3 Christmas Tree with Snow
      • How to Create a Pure CSS3 Slideshow
      • CSS3 Drop Caps
      • Pure CSS3 Slider
      • Fantastic Animated Buttons using CSS3
      • How to Create a Pure CSS3 Animated Photo Gallery
      • Toggle CSS3 Bottom Navigation Bar
      • How to Generate Runtime Multi-columns with CSS3
      • Multiple backgrounds and Animation with CSS3
  • jQuery
    • Photo album with jQuery Fotorama
    • Photo album with jQuery Chop Slider
    • Cool Background Image Sliding effect with jQuery
    • jQuery Templates - Usage Practice
    • Photo Album with Galleriffic jQuery plugin
    • Fantastic Photo Album with TN3
    • Ajaxy Photo Gallery (jQuery) with Custom Images Sets
    • Rotating Slider with Easing Effects in jQuery
    • Animated jQuery Progressbar Plugin
    • Nice CSS3 Lightbox Gallery
    • Photo Album with Highslide
    • Using Flux Slider jQuery plugin
    • Ajaxy Chained Selects
    • Modern jQuery Pagination for Content
    • Your own jQuery Slider Plugin
    • Attractive Photo Gallery using SmartGallery
    • Animated Photo Gallery using jQuery (Slider Kit)
  • PHP
    • Powerful Chat System - Lesson 3
    • Powerful Chat System - Lesson 2
    • Powerful Chat System
    • Access Control with Bit Masks
    • Own XML/JSON/HTML API with PHP
    • Your Own Ajax Poll System
    • Diary style PHP Guestbook
    • Smooth Curve Graphs with PHP and GD
    • Your Own Commenting System from Scratch
    • Autocomplete with PHP, jQuery, MySQL and XML
    • Your Own 5 Stars Voting System
    • How to use Memcache with PHP
    • How to install APC on Linux
    • How to Use APC Caching with PHP
    • Watermark processing on images using PHP and GD
    • ID3 Tags Reader with PHP
    • Advance Level Login system with Logic captcha
    • Protection and Methodologies of Security Vulnerabilities
    • How to Resize images on Server Side
    • How to Protect any Site from Spam using Akismet
    • Phar - PHP archiving practice
  • JS
    • Form Validation with Javascript and PHP
    • Fullscreen Javascript Slide navigation
    • Photo Scrambler grid in javascript
    • Photo Slideshow (zoom fading) effect
    • Custom scrollbars - cross-browser solution
    • Flare Lens Effect
    • Own RSS Reader Using Google Feed API
    • Cross-browser Wave Effects
    • Cross-browser Supported Image Skew effect
  • Res
    • ← Infographic
      • The Evolution of Languages
    • ← jQuery plugin roundups
      • December 2011
      • November 2011
      • 10 fresh jQuery Tutorials
      • October 2011
      • September 2011
      • 10 fresh Ajax related jQuery plugins
      • August 2011
      • 10 Oven Fresh jQuery Plugins for UI
      • 10 Most creative jQuery plugins for tables
      • 10 Most Creative jQuery Navigation Plugins
      • 10 fresh jQuery plugins for working with forms and UI
      • 10 superb jQuery plugins for working with images
    • ← HTML5 stuff
      • HTML5 and Games
      • 10 Fresh HTML5 Tutorials
      • Fresh impressing WebGL demonstrations
      • Most impressing HTML5 with WebGL demonstrations
      • 10 Fresh & Impressive HTML5 Canvas (and WebGL) Examples
      • 10 Exceptional Examples of HTML5 Canvas and Applications
    • ← Mobile
      • How to start developing own applications for Android
      • 10 Fresh Android tutorials
      • 10 Attractive Tutorials for Developing iPhone Applications
      • 10 Attractive android tutorials for developers
      • 10 Fresh iPad Apps for Web Designers & Developers
      • 10 Fresh Android Apps for Web Designers & Developers
      • 10 Fresh iPhone Apps for Web Designers & Developers
      • Top 10 iPhone apps for working with graphics
    • 12 Unique Navigation Menu Designs For Your Inspiration
    • 15 Unique and Creative Layouts 2011
    • 12 Beautifully Creative Flash Websites of 2011
    • Fresh collection of Original Captchas
  • XSLT
    • Animated forums using XSLT and Ajaxy
    • Multilevel Menu using XSLT
    • Delicious bookmarks using XSLT transformation
    • XPath visually
    • Tags cloud using XSLT transformation
    • Youtube videos using XSLT transformation
  • Contact Us
KEEP IN TOUCH

HTML5 Game Development – Lesson 4

Nov21
2011
9 Comments Written by admin
HTML5 Game Development - Lesson 4

HTML5 Game Development – 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 loop this sound), and another sound – dragon’s roar (on mouseup event). And finally we will teach our dragon be closer to the mouse cursor (when we hold down the mouse).

Our previous article you can read here: Developing Your First HTML5 Game – Lesson 3. Our new script is new enhanced version of previous one.

Here are our demo and downloadable package:

Live Demo
download in package

Ok, download the example files and lets start coding !


Step 1. HTML

Here are all html of my demo. Then again, if you are still used to the simple html you can check out
some basic information on html5 here

index.html

<!DOCTYPE html>
<html lang="en" >
    <head>
        <meta charset="utf-8" />
        <title>HTML5 Game Development - Lesson 4 | Script Tutorials</title>

        <link href="css/main.css" rel="stylesheet" type="text/css" />

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

        <footer>
            <h2>HTML5 Game Development - Lesson 4</h2>
            <a href="http://www.script-tutorials.com/html5-game-development-lesson-4/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
        </footer>
    </body>
</html>

Step 2. CSS

Here are used CSS styles.

css/main.css

I will not publish styles today – this is just page layout styles, nothing special. Available in package.

Step 3. JS

js/script.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 <= 0) {
        iBgShiftX = 1045;
    }
    ctx.drawImage(backgroundImage, 0 + iBgShiftX, 0, 1000, 940, 0, 0, 1000, 600);

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

    // in case of mouse down - move dragon more close to our mouse
    if (bMouseDown) {
        if (iLastMouseX > dragon.x) {
            dragon.x += 5;
        }
        if (iLastMouseY > dragon.y) {
            dragon.y += 5;
        }
        if (iLastMouseX < dragon.x) {
            dragon.x -= 5;
        }
        if (iLastMouseY < 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 > dragon.x- dragon.w/2 && mouseX < dragon.x- dragon.w/2 +dragon.w &&
            mouseY > dragon.y- dragon.h/2 && mouseY < 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 > dragon.x && Math.abs(mouseY-dragon.y) < dragon.w/2) {
            iSprDir = 0;
        } else if (mouseX < dragon.x && Math.abs(mouseY-dragon.y) < dragon.w/2) {
            iSprDir = 4;
        } else if (mouseY > dragon.y && Math.abs(mouseX-dragon.x) < dragon.h/2) {
            iSprDir = 2;
        } else if (mouseY < dragon.y && Math.abs(mouseX-dragon.x) < dragon.h/2) {
            iSprDir = 6;
        } else if (mouseY < dragon.y && mouseX < dragon.x) {
            iSprDir = 5;
        } else if (mouseY < dragon.y && mouseX > dragon.x) {
            iSprDir = 7;
        } else if (mouseY > dragon.y && mouseX < dragon.x) {
            iSprDir = 3;
        } else if (mouseY > dragon.y && mouseX > 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
});

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 – draw our dragon. In our code you can find several new interesting methods:

1. Loop background sound

    // '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();

2. Draw sprites

    var oDragonImage = new Image();
    oDragonImage.src = 'images/dragon.gif';
    oDragonImage.onload = function() {
    }
....
    // update sprite positions
    iSprPos++;
    if (iSprPos >= 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);

So, we loading initial image (with set of all sub-images), then – draw part of that image, then shifting its positions, and draw again (loop).

Step 4. Custom files

images/dragon.gif, images/hell.jpg, media/dragon.wav and media/wings.wav

All these files available in our package


Live Demo
download in package

Conclusion

Are you like our new handy dragon? :-) I will be glad to see your thanks and comments. Good luck!

About: admin:
I am web developer with huge experience (in web languages and even in system languages). Also I am the founder of current website (and several another). I like to write blogs about web development/design. Feel free to Follow us on Twitter: tweetmeme_screen_name='AramisGC';
If you Enjoyed our article don't forget to Share the love with your friends.
    Tweet
   
   
Written by: admin on November 21, 2011.
Last revised by: admin
on December 28, 2011.

Related Stuff You Will Love!

  1. HTML5 Game Development – Navigating Your Spaceship- Lesson 3
    HTML5 Game Development – Navigating Your Spaceship- Lesson 3
  2. HTML5 Game Development – Lesson 2
    HTML5 Game Development – Lesson 2
  3. HTML5 Game Development – Lesson 5
    HTML5 Game Development – Lesson 5
  4. HTML5 Game Development – Lesson 7
    HTML5 Game Development – Lesson 7
Posted in HTML5, JavaScript
SHARE THIS Twitter Facebook Delicious StumbleUpon E-mail
« Cool Background Image Sliding effect with jQuery
» 10 fresh jQuery Tutorials

8 Comments

  1. WM's GravatarWM
    November 30, 2011 at 5:43 am | Permalink

    http://www.script-tutorials.com/tag/game/

    You forgot to add the ‘game’ tag.

    Sorry for the rude request, but I think that you should write an new post to list the series of tutorial entry link, that would be good for promoting or bookmarking.

    Thanks for your nice work!

  2. admin's Gravataradmin
    November 30, 2011 at 5:57 am | Permalink

    Hello WM,
    Do you mean – create list of all previous game-related tutorials in bottom of each game lesson?

  3. WM's GravatarWM
    November 30, 2011 at 6:51 am | Permalink

    Sorry for my poor English, I’m Taiwanese.

    I mean like that: http://net.tutsplus.com/sessions/python-from-scratch/

  4. admin's Gravataradmin
    December 8, 2011 at 1:28 pm | Permalink

    So, do you like to see all related articles (of same session / series) in one place like here?

  5. WM's GravatarWM
    December 12, 2011 at 2:35 am | Permalink

    Yes, sharing one link is much easier than multiple links, isn’t it?

    I’ve seen some journal sites do this way, they posted an introductory index post , and then posted the first article of the series, when proceeding articles was posted, they updated the index post to add links.

    There is another way, posting the index post with conclusion after the series ends, but I think the former is better, for that it could make the index post to be spread early.

  6. Judith's GravatarJudith
    December 18, 2011 at 5:19 pm | Permalink

    Outstanding! But when coming from another site, your #3 tutorial did not have the right link.

    http://www.script-tutorials.com/html5-game-development-navigating-your-spaceship-lesson-3/

    It would make it Ez-ier for people if you had a link at the bottom of each of your tutorial pages to your next tutorial.

    In fact I had to go to Lesson 4 to get the link for Lesson 3.

    Because you start out with this URL for Lesson 1
    http://www.script-tutorials.com/html5-game-development-lesson-1/
    http://www.script-tutorials.com/html5-game-development-lesson-2/
    Different for Lesson 3 (see above)
    And then Lesson 4 is:
    http://www.script-tutorials.com/html5-game-development-lesson-4/

  7. admin's Gravataradmin
    December 21, 2011 at 6:04 pm | Permalink

    Hello Judith,

    Thanks for your remarks, I am going to think about it. Generally I want to create extra alternative navigation for more comfort access to our articles (maybe put it into dropdown menu, with sorting by categories)

  8. admin's Gravataradmin
    December 22, 2011 at 5:31 am | Permalink

    Thanks for your idea, right now I’m thinking about adding alternative navigation menu to website (dropdown) where will be listed all articles by categories.

  1. Top 10 Reasons to Use HTML5 Right Now | on December 14, 2011 at 7:25 am

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

*

*

CAPTCHA Image
Refresh Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Popular Tutorials

  • How to create easy pagination with jQuery
  • Animated jQuery Progressbar Plugin
  • Pure HTML5 file upload
  • How to Create Animated Photo Gallery using jQuery (Slider Kit)
  • CSS3 Image Hover Effects
  • Creating a HTML5 & CSS3 Single Page Web Layout
  • How to Easily Make a PHP Chat Application
  • Autocomplete with PHP, jQuery, MySQL and XML

Tags

3d AJAX android animated animation app application applications apps canvas captcha chat system coding creating css css3 developers dropdown effect flash fresh gallery how-to html html5 image images iphone javascript jQuery layout menu navigation new photo PHP plugin plugins slideshow system tutorial tutorials webgl website xslt

Recent Tutorials

  • HTML5 Video player jQuery plugin
  • Pure CSS3 Accordion
  • HTML5 charts and graphs
  • Infographic: CSS3 Properties
  • 10 HTML5 canvas examples for Valentine’s Day
  • Powerful Chat System – Lesson 4
  • CSS3 multicolor menu
  • New HTML5&CSS3 single page layout – Fashion

Friends

  • X-Musics

Tutorials for Web Developers Copyright © 2009-2011 Script tutorials · All rights reserved