DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Languages
  4. HTML5 Game Development – Lesson 4 - Sprites and Sounds

HTML5 Game Development – Lesson 4 - Sprites and Sounds

Andrey Prikaznov user avatar by
Andrey Prikaznov
·
Nov. 28, 11 · Interview
Like (0)
Save
Tweet
Share
3.90K Views

Join the DZone community and get the full member experience.

Join For Free
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.

index.html

01 <!doctype html>
02 <html lang="en" >
03 <head>
04 <meta charset="utf-8" />
05 <title>html5 game development - lesson 4 | script tutorials</title>
06
07 <link href="css/main.css" rel="stylesheet" type="text/css" />
08
09 <!--[if lt ie 9]>
10 <script src=" http://html5shiv.googlecode.com/svn/trunk/html5.js "></script>
11 <![endif]-->
12 <script src=" http://code.jquery.com/jquery-latest.min.js "></script>
13 <script type="text/javascript" src="js/script.js"></script>
14 </head>
15 <body>
16 <div class="container">
17 <canvas id="scene" width="1000" height="600"></canvas>
18 </div>
19
20 <footer>
21 <h2>html5 game development - lesson 4</h2>
22 <a href=" http://www.script-tutorials.com/html5-game-development-lesson-4/ " class="stuts">back to original tutorial on <span>script tutorials</span></a>
23 </footer>
24 </body>
25 </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

001 // inner variables
002 var canvas, ctx;
003 var backgroundimage;
004 var ibgshiftx = 100;
005 var dragon;
006 var dragonw = 75; // dragon width
007 var dragonh = 70; // dragon height
008 var isprpos = 0; // initial sprite frame
009 var isprdir = 4; // initial dragon direction
010 var dragonsound; // dragon sound
011 var wingssound; // wings sound
012 var bmousedown = false; // mouse down state
013 var ilastmousex = 0;
014 var ilastmousey = 0;
015 // -------------------------------------------------------------
016
017 // objects :
018 function dragon(x, y, w, h, image) {
019 this.x = x;
020 this.y = y;
021 this.w = w;
022 this.h = h;
023 this.image = image;
024 this.bdrag = false;
025 }
026 // -------------------------------------------------------------
027
028 // draw functions :
029 function clear() { // clear canvas function
030 ctx.clearrect(0, 0, ctx.canvas.width, ctx.canvas.height);
031 }
032
033 function drawscene() { // main drawscene function
034 clear(); // clear canvas
035
036 // draw background
037 ibgshiftx -= 4;
038 if (ibgshiftx <= 0) {
039 ibgshiftx = 1045;
040 }
041 ctx.drawimage(backgroundimage, 0 + ibgshiftx, 0, 1000, 940, 0, 0, 1000, 600);
042
043 // update sprite positions
044 isprpos++;
045 if (isprpos >= 9) {
046 isprpos = 0;
047 }
048
049 // in case of mouse down - move dragon more close to our mouse
050 if (bmousedown) {
051 if (ilastmousex > dragon.x) {
052 dragon.x += 5;
053 }
054 if (ilastmousey > dragon.y) {
055 dragon.y += 5;
056 }
057 if (ilastmousex < dragon.x) {
058 dragon.x -= 5;
059 }
060 if (ilastmousey < dragon.y) {
061 dragon.y -= 5;
062 }
063 }
064
065 // draw dragon
066 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);
067 }
068
069 // -------------------------------------------------------------
070
071 // initialization
072 $(function(){
073 canvas = document.getelementbyid('scene');
074 ctx = canvas.getcontext('2d');
075
076 var width = canvas.width;
077 var height = canvas.height;
078
079 // load background image
080 backgroundimage = new image();
081 backgroundimage.src="images/hell.jpg";
082 backgroundimage.onload = function() {
083 }
084 backgroundimage.onerror = function() {
085 console.log('error loading the background image.');
086 }
087
088 // 'dragon' music init
089 dragonsound = new audio('media/dragon.wav');
090 dragonsound.volume = 0.9;
091
092 // 'wings' music init
093 wingssound = new audio('media/wings.wav');
094 wingssound.volume = 0.9;
095 wingssound.addeventlistener('ended', function() { // looping wings sound
096 this.currenttime = 0;
097 this.play();
098 }, false);
099 wingssound.play();
100
101 // initialization of dragon
102 var odragonimage = new image();
103 odragonimage.src="images/dragon.gif";
104 odragonimage.onload = function() {
105 }
106 dragon = new dragon(400, 300, dragonw, dragonh, odragonimage);
107
108 $('#scene').mousedown(function(e) { // binding mousedown event (for dragging)
109 var mousex = e.layerx || 0;
110 var mousey = e.layery || 0;
111 if(e.originalevent.layerx) { // changes for jquery 1.7
112 mousex = e.originalevent.layerx;
113 mousey = e.originalevent.layery;
114 }
115
116 bmousedown = true;
117
118 if (mousex > dragon.x- dragon.w/2 && mousex < dragon.x- dragon.w/2 +dragon.w &&
119 mousey > dragon.y- dragon.h/2 && mousey < dragon.y-dragon.h/2 +dragon.h) {
120
121 dragon.bdrag = true;
122 dragon.x = mousex;
123 dragon.y = mousey;
124 }
125 });
126
127 $('#scene').mousemove(function(e) { // binding mousemove event
128 var mousex = e.layerx || 0;
129 var mousey = e.layery || 0;
130 if(e.originalevent.layerx) { // changes for jquery 1.7
131 mousex = e.originalevent.layerx;
132 mousey = e.originalevent.layery;
133 }
134
135 // saving last coordinates
136 ilastmousex = mousex;
137 ilastmousey = mousey;
138
139 // perform dragon dragging
140 if (dragon.bdrag) {
141 dragon.x = mousex;
142 dragon.y = mousey;
143 }
144
145 // change direction of dragon (depends on mouse position)
146 if (mousex > dragon.x && math.abs(mousey-dragon.y) < dragon.w/2) {
147 isprdir = 0;
148 } else if (mousex < dragon.x && math.abs(mousey-dragon.y) < dragon.w/2) {
149 isprdir = 4;
150 } else if (mousey > dragon.y && math.abs(mousex-dragon.x) < dragon.h/2) {
151 isprdir = 2;
152 } else if (mousey < dragon.y && math.abs(mousex-dragon.x) < dragon.h/2) {
153 isprdir = 6;
154 } else if (mousey < dragon.y && mousex < dragon.x) {
155 isprdir = 5;
156 } else if (mousey < dragon.y && mousex > dragon.x) {
157 isprdir = 7;
158 } else if (mousey > dragon.y && mousex < dragon.x) {
159 isprdir = 3;
160 } else if (mousey > dragon.y && mousex > dragon.x) {
161 isprdir = 1;
162 }
163 });
164
165 $('#scene').mouseup(function(e) { // binding mouseup event
166 dragon.bdrag = false;
167 bmousedown = false;
168
169 // play dragon sound
170 dragonsound.currenttime = 0;
171 dragonsound.play();
172 });
173
174 setinterval(drawscene, 30); // loop drawscene
175 });

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

1 // 'wings' music init
2 wingssound = new audio('media/wings.wav');
3 wingssound.volume = 0.9;
4 wingssound.addeventlistener('ended', function() { // looping wings sound
5 this.currenttime = 0;
6 this.play();
7 }, false);
8 wingssound.play();

2. draw sprites

01 var odragonimage = new image();
02 odragonimage.src="images/dragon.gif";
03 odragonimage.onload = function() {
04 }
05 ....
06 // update sprite positions
07 isprpos++;
08 if (isprpos >= 9) {
09 isprpos = 0;
10 }
11
12 // draw dragon
13 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!

source: http://www.script-tutorials.com/html5-game-development-lesson-4/

Sprite (computer graphics) HTML

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The Path From APIs to Containers
  • REST vs. Messaging for Microservices
  • How to Submit a Post to DZone
  • HTTP vs Messaging for Microservices Communications

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: