The Karma Project: Code Less, Teach More

December 17, 2009

Tutorial IV: The Adventure Continues – JavaScript and SVG

Filed under: News — Tags: , , , , — bryanwb @ 7:08 pm

This article is the fourth in a series of four

  1. Introduction to karma.js
  2. This article,Comparing HTML 5 Canvas and SVG
  3. Digging into Inkscape
  4. This article, JavaScript and SVG

Section II: Writing the HTML . . . 5!

Step 1: It’s all about the !DOCTYPE

It all starts with the doctype, please make sure document starts with the following doctype declaration

<!DOCTYPE html>

DO NOT USE the following

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
     "http://www.w3.org/TR/html4/strict.dtd"> 

Karma will throw a big fat ugly error message and be otherwise unkind

Step 2: Put the JavaScript in

    <script type="text/javascript" src="../../js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="../../js/karma.js"></script>
    <script type="text/javascript" src="../../js/jquery.svg.js"></script>
    <script type="text/javascript" src="../../js/jquery.svgdom.js"></script>
    <!-- Put your code in lesson.js, please -->
    <script type="text/javascript" src="js/lesson.js"></script>

Step 3: You should <object>

Please use <object> tag to embed your SVG into the HTML

Step 4: Don’t put style information into the document, put it in lesson.css

Please don’t do the following

<div id="badDiv" style="display:inline;font-size:bigger;"> Karma Rulez! </div>

The “Karma Rulez!” part is excusable but please don’t use the
style attribute. It is not only bad practice but it
will totally screw up the as-yet-unwritten internationalization
library mundo.js

Section III: The Presentation Layer with CSS

Good News, you can use the same CSS file for both your html and SVG
To use an external css file in your SVG, you need to link it in just above the first <svg> tag.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet href="../../css/lesson.css" type="text/css"?>
<svg ......

We want to make sure that the text on the map and the spaceship are invisible. Let’s also make the cursor become a pointer when it moves over a capital icon.

.text { display: none; }
.capital.city { cursor: pointer;}
.spaceship { display: none;}

Much of our program logic will be to reveal elements of the map and the spaceship when the user answers correctly.

CSS is a complicated, tricky beast that I can’t begin to explain here. Let’s move onto something easy, like JavaScript!

Section IV: Writing the game logic with JavaScript

Step 1: Meet jQuery, jQuery meet you

jQuery is a fantastic library for interacting with the HTML Document
Object Model or DOM. What is this &^&$$! DOM? The DOM is the
programming interface for HTML in the browser. Working with it
directly is pretty painful but jQuery abstracts it to something that
is actually quite pleasant to work with. We start with jQuery using the following:

$(document).ready(
    function(){
        //Once the HTML on this page has fully loaded,
	// run my code here
        
    }
);

$(document).ready doesn’t mean that everything is ready. It only means that all the html and <img> elements have finished downloading. It does not mean than any <audio>, <video>, or <svg> elements have finished downloading. This is important as your program will fail if it tries to manipulate any of these elements before they are ready.

Step 2: Tell Karma about your assets and Karma will put them into collections

	var k = Karma({
			  svg :[    
                              {name:'capitals', domId: 'capitals'},
			      {name:'alien', domId: 'alien'},
			      {name:'spaceship', domId: 'spaceship'},
			      {name: 'help', domId: 'helpScreen'},
			      {name:'playAgain', domId:'playAgain'},
			      {name:'helpIcon', domId:'helpIcon'},
			      {name:'quitIcon', domId:'quitIcon'}
			  ],
			  audio:[
			      {name:'correct', file:'correct.ogg'},
			      {name:'incorrect', file:'incorrect.ogg'}
			  ]
	});

The Karma() method initializes Karma.karma object with assets we pass
to it. During this initialization, the svg array we pass in is
converted to the “collection” object k.svg. You can access any of the values k.svg
using the name you passed in as the key. The ‘name’ property is arbitrary. I use this instead of the filename or domID because those can often be lengthy.

var mySvg = k.svg.helpIcon  //same as <svg id="helpIcon">
var myHeight = k.svg.helpIcon.height;
var myWidth = k.svg.helpIcon.width;

var name = 'playAgain';
var mySvg2 = k.svg[name];  //you can reference different assets programmatically

//You can even loop through the entire collection, but remember a collection
//is an object and not an array
$.each(k.svg, function(mySvg){ mySvg.css('display', 'none');

Accessing these items using the collections has an optional
performance benefit. Every time you use a css selector such as
document.getElementByid(‘someId’) or $(‘#someId’), you run a search
through the entire DOM.

Karma currently supports five different collection types, k.audio,
k.canvas, k.svg, and k.video. Please note that the prefix ‘k’ is an
arbitratry shortcut to Karma.karma and not by default part of the
global scope.

Karma will also throw errors if any of these assets can’t be
loaded. You will probably find this very helpfulin debugging your
application. Karma() also attaches helper methods and properties.

You do not have to tell Karma about all the images, svg images, and audio files in your application. You only need to tell Karma about the ones you want to helper methods for and to be fully loaded when you call Karma.ready()

Step 2: Get Ready!

Most likely, you won’t want to start our program until all of our assets are ready. $(document).ready only makes sure that the HTML and images have loaded. For this reason, Karma provides Karma.ready(), which blocks your program from running until all the assets you told it about in Karma( ) have fully loaded.

$(document).ready(
    function(){
	var k =	Karma({ /* tell Karma about your assets */});
	
	k.ready(function (){

        //Once the HTML on this page has fully loaded,
	// run my code here
	}        
    }
);

You have to wrap your code in function () { } otherwise it will
execute immediately, without waiting for Karma to be ready().

Step 3: Attach Event Handlers to the capitals on the map



 $.map($('.capital.city', capRoot), function(elem){
		$(elem, capRoot).bind('click', function(event) {
                        if (isActive){
		             checkAnswer(event.target);
                        } else {
                               return;
                        }
	       });
}); 
// $('.capital.city', capRoot)  is a CSS selector that matches every city icon on the map
// $.map( )  executes the anonymous function on each matching item
// .bind() is a jQuery method that attaches an Event Listener
// isActive is a global variable, when the game is paused, it is false
// When the game is paused rather than removing the event handler, simply set isActive to false

Step 4: Make the alien talk

This is easy, use jQuery’s text() method to change the text

The CSS selector ‘foreignObject #alienQuestion’ matches an element with the id alienQuestion preceded by a foreignObject tag. For some reason it doesn’t work without including foreignObject in the selector. Perhaps this is a quirk having to do with using the foreignObject tag.

 $('foreignObject #alienQuestion', k.svg.alien.root).text('some Text');

Step 5: When user makes correct choice, display text and reveal part of the spaceship

//complex command that splits out a part name from those not yet displayed
var part = parts.splice(0,1)[0];  

//previously display for these items was set to 'none', 'block' makes them visible again
$('#' + part, spaceshipRoot).css('display', 'block');
$('foreignObject #alienQuestion', k.svg.alien.root).text("Correct! " + question.capitalName               
    +  " is the capital of " + question.deptName);
//display the text of State and capital 
$('.text.' + question.dept, capRoot).css('display', "block");

Step 6: Make the spaceship fly away

	    var flyAway = function(){
		var isLaunching = true;
          
		var startEngines = function(){
		var shipFire1 = $('#shipFire1', spaceshipRoot);
		var shipFire2 = $('#shipFire2', spaceshipRoot);
		var toggle = true;		    
		    
	   //this animation alternates the display of two images
           //to simulate rocket propulsion
	    var toggleFires = function(){			
			if(isLaunching){
			    if(toggle){
				shipFire1.css('display', "none");
				shipFire2.css('display', "block");
			    }else{
				shipFire1.css('display', "block");
				shipFire2.css('display', "none");
			    }
			    //toggle fires
			    toggle = !toggle;
			    setTimeout(toggleFires, 400);
			}
		    };

		    toggleFires();	     
		};

		
		var fly =  function(){
		    $('#spaceship').animate({"bottom":"550px"}, 
			    {"duration":8000, 
			    "complete": function(){ 
				isLaunching = false;
				showPlayAgain();
			    }});
		};

		var blastOff = function(){
		    startEngines();
		    setTimeout(fly, 2000);				   
		};

		blastOff();
		
		
	    };

Step 7: Dialog Boxes

This part is actually quite easy

A ‘dialog box’ is nothing more than an absolutely positioned <div>

The following code takes a div element that previously hidden and centers it in front of everything else in the screen using the ‘z-index’ property

$('#helpScreen').css({"position": "absolute",
				"width": "420px", "height": "360px",
				'top': '25px', 'left': '20%',
				'z-index' : 20,  'display':'block', "opacity": 1});

For further exploration, I highly recommend reading through the original source code.
I haven’t explained every part of this exercise in detail so please leave me comments with what you don’t understand or think should be explained in greater detail.

4 Comments »

  1. [...] JavaScript and SVG [...]

    Pingback by An Introduction to karma.js – Making HTML 5 Easy « Karma Project Learn.Teach.Everything — December 18, 2009 @ 3:30 am

  2. [...] JavaScript and SVG [...]

    Pingback by Tutorial III: Digging into Inkscape « Karma Project Learn.Teach.Everything — December 18, 2009 @ 3:34 am

  3. [...] JavaScript and SVG [...]

    Pingback by Karma version 0.2 Released « Karma Project Learn.Teach.Everything — December 20, 2009 @ 4:24 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Shocking Blue Green Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: