Rodrixar

Saturday, August 16

2D game development in JavaScript with AngularJs

2D game development in JavaScript with AngularJs and Google Closure tools http://goo.gl/Iqmb5a

Friday, March 8

HTML5 Jelly Gravity Game Demo: SVG, Drag & Drop

This is a demo of a 2D HTML5 game I'm working on for a book I'm writing. The book will be published later this year under the title "Learning HTML5 by Creating Fun Games," ISBN 978-1-84969-602-9.

Friday, July 6

Apple to Sue Catholic Church Over Slide to Unlock


Apple has sued the Catholic church to block use of its door unlocking system. According to Apple, many of the doors used by the church use slide to unlock technology, which is patented by the company in their iPod, iPhone, and iPad systems. This is a similar case to Google's Android law suit.



According to the complaint, which was filed in a California court earlier today, nobody is allowed to use a sliding motion in the unlocking process of anything - which is very different from a slide to lock use case. Other old style churches are said to be at risk of being sued. This is good news to modern door makers, since it is expected that close to a hundred million doors be replaced within the next 6 months due to Apple's aggressive slide to unlock patent protection.

Thursday, July 5

Apple to Sue San Diego Zoo over a Lion


Apple to Sue San Diego Zoo over a lion



Apple has sued the San Diego Zoo to block use of its lion. According to Apple, the animal owned by the zoo looks too much like the lion used by the company in pictures used to promote  its new operating system.


According to the complaint, which was filed in a California court earlier today, people were having a hard time telling the two lions apart. A deal might be reached between the two parties involved, provided that, along with a fine of $32,000,000,000 (32 billion U.S. dollars), the zoo shaves the feline's mane.

#BoycottApple

Apple to Sue United States over July 4th Fireworks

Apple to Sue United States over July 4th Fireworks


Apple has sued the United States of America to block fireworks in the country. According to Apple, some colors put out by fireworks during last night's celebrations were patented by them just prior to the launch of the iPad. 

According to the complaint, which was filed in a California court earlier today, vivid, bright, and happy colors can only be displayed on the iPad. Apple is also waiting for other countries to use fireworks during moments of celebration to file formal complaints at an international level. It is expected that January 1st, 2013 will be a profitable day for the company, given the number of fireworks users across the planet.

A formal licensing deal is in the works that would allow fireworks makers to continue to sell their products, but this time in the form of an iPad app. Apple says that allowing just any app developer to make a fireworks apps is now against the policy that governs the app store.

#BoycottApple

Wednesday, June 13

Learn How to Speed Read


Why Read Fast or At All

Anyone can read faster
 The average adult can only read an average of 250 words per minute (WPM). Given that an average novel has between 90,000 and 140,000 words, it would take an average person 6 to 9 hours to read a book (provided that it was all read in one session, and very consistently, and with absolutely no interruptions or distractions). Of course, most people don’t have this kind of time, patience, or attention span.

On the other hand, the average speed reader can maintain an average of 600 WPM, with the same comprehension and retention rate. Through special speed reading training, people have consistently broken the 1,000 WPM barrier. So-called “professional speed readers” achieve reading rates upwards of 2,000 WPM, with higher comprehension and retention than both the average reader and average speed reader. The current fastest reader in the world is said to reach close to 5,000 WPM with average understanding of the material read.

Speed Reading Techniques

It turns out that anyone who wants to increase their reading speed can do so. With minimum proper practice, people can nearly double their reading speed. In this article, I will introduce two simple techniques that you can start using today, and start reading faster immediately.

The two main issues that slow people down are subvocalizing words in their head, and looking back to re-read words. The first of these issues is the reason that people read about as fast as they can speak. To break the habit of backtracking (looking back at the same line of text read previously), one only needs to train his or her eyes. Techniques that help with this include moving your finger below the line of text being read, and following your finger with your eye. Move your finger at a constant rate, and soon your eye will get used to scanning a line of text at that speed. Eventually no finger is needed to guide the eye.


Train your eyes to move faster through the page
The best way to stop sounding out words in your head is to simply be conscious about the fact, and simply “photograph” the word with your eye, and let your eye take care of registering what the meaning of the word is. With practice, you will see how amazing this is. At first some people don’t even believe that this is possible. Think about it, though. When you see the shape of a heart drawn somewhere, you need only get that image in front of your eyes, and your brain instantly identifies with the image. You don’t need to sound out the word “heart”, “love”, or “passion” in your head. Your brain has a particular connection with the symbol (the shape, to be more specific). The same thing is true of words, but since most people aren't taught this principle, they never think about it. The truth is that your eyes word independent of your ears, and your brain need only a fraction of a second to register thoughts meaning.


 

Speed Reading Software

While reading from a book is more natural and comfortable to most people, the best speed reading programs today come in the form of software. More particularly, the best tools available today to help you become a faster reader are online reading software.

The faster you read, the more books you can finishThere are many reasons that learning to speed read on a computer screen is such a powerful thing. For one, since the definition of most monitors isn’t as high as print paper, once your eyes are used to visualizing words on a screen, you’ll achieve faster rates when reading on paper. Also, since there are more content available digitally each day, being able to read quickly on a screen is a great skill, which pays off very quickly and very generously.

The very best speed reading software that I know of is an app available on the Google Chrome web browser. You can get the app directly from the Chrome Web Store. The app is called Speed Reading Trainer, and is one of the most used educational web app today. Great for young people and adults alike. Highly recommended.


Get the Speed Reading Trainer Now

Finish more books, and get your homework done faster with the help of this amazing piece of software. Works on laptops, netbooks, desktops, on Windows, Mac, Linux, you name it. Any device that runs Google Chrome web browser supports the app. Get the app now or click the image below

Don't let your eyes slow you down

Monday, April 9

5 Awesome WebGL Demos to Inspire Web Developers & 3D Artists

Here are 5 simple, yet amazing WebGL demos that I think should be shared more so more web developers and designers can catch the view of 3D development on the browser. These demos range from really easy (to encourage the beginners and newcomers), to really advanced, complex, and just plain complicated (meant to inspire and encourage the HTML5 masters, and open the eyes of the C++ and OpenGL veterans out there).


Parsing 3D Model from Blender in OBJ File Format: Part 1

This OpenGL demo show how to load advanced models into a scene, instead of simply rendering the usual gradiated OpenGL triangle and square. It talks about how to use the common .obj file format to load vertices, normals, and UV coordinates that make up your 3D model object. The demo is done in C++ and the model is sculpted in and exported from Blender.


Parsing 3D Model from Blender in OBJ File Format: Part 2 Texture & Advanced Lighting

The second part of the previous demo. This goes into detail on how to load texture files into your 3D model objects, how to simulate light, and how to produce more realistic, and cool artistic lighting effects in OpenGL. The fragment and vertex shader programs used in this demo is written in GLSL, which means it can be used direclty (without any changes at all) in WebGL, or OpenGL ES on a mobile device (such as the iPhone, iPod touch, iPad, and any Android device that supports WebGL).

Grass Fields

This WebGL demo shows a field with a lot of grass, which move very realistically with the wind. One of the earlier WebGL demos, which is still very impressive.


Jellyfish

Another demo that attempts to simulate life. This one shows beautiful water effects reflecting off the Jellyfish. This WebGL demo runs at about 24 frames per second pretty consistently in most newer browsers.


Liquid Galaxy

Finally, this is the classic Google powered WebGL demo. It shows the popular fish bowl, except that it renderes the scene in 8 different computers at the same time. The demo is meant to show off how powerful HTML5 can be. The demo uses web sockets to synchronize all 8 computers, the canvas tag (with a 3D context, of course) to display the aquatic scenery, and web workers to calculate where each model should be, where each vertex should be moved to, etc.

Saturday, July 16

HTML5 WebSocket Server in PHP


This is a video demo of my Javascript stock exchange simulator programmed in HTML5 and PHP. I'm running my websocket server using WAMP (Windows, Apache, MySQL, and PHP). Let me know if you have any questions or comments about any of this.




Get the source code today
If you're interested in playing around with this websocket server, you can download the source code for it at my official website.


Friday, July 15

How to run PHP sockets in WAMP


Lately I've been playing around with HTML5 Web Sockets. This has been pretty fun and educational. Especially since I've ran into a few problems, and very little documentation is available on it. After resisting the temptation of pulling my hair out (since I don't have a whole lot of it left, anyways), and focusing on finding answers to these problems, I was rewarded by a generous universe, who revealed me all the answers I needed. This post will cover 3 ways to help you solve the common error you may run into when attempting to create sockets in PHP using WAMP (Windows, Apache, MySQL, and PHP). This error message says Call to undefined function socket_create().

How to fix Call to undefined function socket_create()

If you're running WAMP, there are two basic ways to fix this. This error is caused by a simple WAMP/PHP configuration that you left out. What you want to do is pretty simple. Simply enable sockets in PHP. To do so, you must:
  • Click the WAMP icon
  • Select PHP
  • Select PHP Extensions
  • Enable the php_sockets extension

Now try restarting all services in your WAMP, and see if the sockets work now. This should solve the problem 9/10 times. However, there are some situations when you will do just what I described above, and your PHP sockets will still return that undefined function socket_create(), which will be frustrating. However, here are some other things that will fix this problem:

Set up your environment variables to run PHP from the command line

A few weeks ago I posted a tutorial on how to run Python from the command line, where I describe how to set up the environment variables in Python. The exact same process is used for PHP and WAMP, so you can use that as a reference. The steps are simple:
  • Click the WAMP icon
  • Select www directory
  • This will take you to the directory where WAMP is installed. Go up one directory level from the www folder, and select the bin directory. Inside bin you will see a PHP directory, inside of which there will be a PHP5.3.4 (whatever version of PHP you happen to have installed). Follow this directory path until you find the one that has a file named php.exe
  • Copy the complete path to this directory
  • In your environment variables window (follow the Python article on the specifics on how to get there), edit the PATH variable, and paste this path to your PHP.exe (the PHP interpreter) file that you copied in the previous step

Now you should be able to go do a DOS window and type in a command like:

php file.php

(assuming that you're in a directory that has a file named file.php, of course)

This will execute your script right in the command window. If you're trying to run a PHP socket server so clients can connect to it, you will need to run it from a terminal (command line), and this is how you set it up.

However, there are 2 more ways to solve the socket problem ("undefined function socket_create()"). They're both pretty similar, although the second one is less obvious.

Method #1: Edit your php.ini file

This basically accomplishes the exact same thing you did in the fist thing I suggested earlier in this PHP tutorial. What you need to do is:
  • Click the WAMP icon
  • Select PHP
  • Select php.ini
  • Search your php.ini file for the following line:

    ;extension=php_sockets.dll

  • This line has a semi-column at the beginning, meaning that the sockets extension is disabled. To fix this, simply uncomment the statement, and save the php.ini file. To uncomment this line of code, simply delete the semi-column, changing the line to this:

    extension=php_sockets.dll


Again, after restarting all WAMP services, try running your PHP script with the create_socket() function call, and things should work out just fine now.

Method #2: Edit the other php.ini file

Sometimes your WAMP will install weird, and the PHP will point to a different php.ini file than the one you can access through the WAMP icon. I'm not sure how this can happen, but without using the technique I'll show here, the problem with the sockets will never go away. I came across this problem when I installed WAMP in a virtual machine running Ubuntu (the virtual machine had Windows XP installed in it). To find out what php.ini your PHP is looking at, go to a command line and type in the following PHP command:

php --ini

This will list the information (file paths) about the configuration of your PHP that you need to edit. The second line of the output you get from this step shows where the true php.ini file is located. Go to that path and uncomment the line that points to the sockets.dll file as described in the previous step.

The output from the php --ini command will look something like this:

C:\Users\Rodrixar>php --ini
Configuration File (php.ini) Path: C:\Windoows
Loaded Configuration File: C:\wamp\bin\php\php5.3.4\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed: (none)


Notice how in this case the .ini file is located within my WAMP folder, which is why the other steps shown in this tutorial worked. But some times this location will be different from the WAMP install location, and by changing that php.ini file you will be able to truly enable and use those desired PHP sockets.

Saturday, July 9

HTML5 Canvas Animation Tutorial with Nintendo Battletoads



Lately I've been playing around with 2D animations in the canvas element. I know that 3D WebGL is the cool thing nowadays, but for now, I'd like to get pretty good with regular, 2 dimensional animations with the boring, old canvas. Below is a demo of what I've come up with so far. Use the right and left arrow on the key board to more Pimple around (actually, I'm not sure if that's Rash or Zits from the original Nintendo game Battletoads...






Sprite animation in the HTML5 canvas

While this is a tutorial, and you've probably come to this article in an attempt to learn how to animate your own canvas and make cool 2D games in HTML5 and Javascript that can be played on the browser, the main reason I'm posting this is because I'd like to learn more about canvas animation myself. Right now I'm just doing things in a way that makes sense to me, but most likely doesn't follow 2D tile-based sidescroller games best practices. So I guess we'll learn together...

To start out, here's the sprite image I'm animating in this HTML5 demo:

Battletoads sprite sheet

I just found this online, in case you wonder... But what I do is pretty simple, as described in this pseudo-code:

  1. Make an *array with the location of each animation frame
  2. Make a variable that keeps track of the current frame being printed from the sprite sheet
  3. Load the sprite sheet image
  4. Draw a portion of the sprite sheet into the canvas. This is where the array created in step 1 comes in
  5. Increment the frame variable using **modular math
  6. If before drawing the next frame (this should be step 4, but makes sense to explain it here), clear the part of the canvas context where the current sprite frame is drawn

* This is an array of objects, each with the (x,y) position of where each animation frame is located within the sprite sheet, plus a (w,h) pair representing the frame's width and height:

var spriteFrames = [
   {x: 0,  y: 0, w: 32, h: 30},
   {x: 33, y: 3, w: 42, h: 27},
   {x: 78, y: 5, w: 30, h: 33}
];

Something like that. Note that each frame can have its own dimensions. The image will still be drawn properly (lined up with the previous and next frames) this way, even if the frame is shorter or wider.

** By modular math I mean that you should increment the variable that keeps track of the current frame using the modulus operator. This way you don't have to worry about going out of bounds in your array, like such:

// a lot of people do this:
currentFrame++;
if( currentFrame > totalFrames - 1)
  currentFrame = 0;

/*** WHAT A WASTE OF BYTES! ***/

// this is how you should increment your current frame index:
currentFrame = (currentFrame + 1) % totalFrames;

/**********************************
 *
   WHAT? but why do that?
   well... follow the math. If you're not familiar the % (MOD) operator,
   it simply performs division, then returns the remainder, which is never
   greater than the number being divided by, which means you always stay
   within the array bounds.

   var totalFrames = 3;
   var currentFrame = 0;

   currentFrame = (currentFrame + 1) % totalFrames;
   -> currentFrame = (0 + 1) % 3 = 1 % 3 = 1

   currentFrame = (currentFrame + 1) % totalFrames;
   -> currentFrame = (1 + 1) % 3 = 2 % 3 = 2

   currentFrame = (currentFrame + 1) % totalFrames;
   -> currentFrame = (2 + 1) % 3 = 3 % 3 = 0

   currentFrame = (currentFrame + 1) % totalFrames;
   -> currentFrame = (0 + 1) % 3 = 1 % 3 = 1
 *
 ***********************************/   

Clearly, incrementing the frame pointer with one operation is better in most cases, but I'm sure there might be cases where something more verbose might be needed, but for the most part, using the MOD operator will save you time and space.

Other than that, I think I need to research this some more and practice what I learn. As you can see in the demo, the animation only works one way. That is because the original image (the sprite sheet) is drawn like that. There is a simple way to flip the image resource being drawn onto the canvas, but that sort of sounds like it takes a more computations than needed. I'm thinking just having a second sprite sheet with the images mirrored should do the trick. It'll take more space in memory, but once loaded, the animation can run without costing CPU power forever.

Also, my animation doesn't quite seem very smooth. This is not because of the strategy used to animate the canvas, but because the sprite sheet is probably not right. One thing I do have in this demo is that every so many milliseconds the timer is fired, the frame pointer is updated, the (x,y) coordinates of the Nintendo character is updated, and the image is redrawn. However, the animation only takes place if at least so many milliseconds have elapsed since the previous animation frame was updated:

// function drawCharacter() { canvasContext.drawCharacter( frame, x, y ); }

// our main Player object has an attribute frameUpdated, 
// which is the time it was last updated (in milliseconds)
function updateAnimationFrame()
{
  if( Date.now() - Player.frameUpdated > 70 )
  {
    Player.currentFrame = (Player.currentFrame + 1) % Player.totalFrames;

    // update time frame was animated
    Player.frameUpdated = Date.now();
} 

Anyway, post your questions, comments, and suggestions.

Thanks, and enjoy!

Tuesday, July 5

Cool CSS3 Tip: Text-Overflow = Ellipsis



You don't have to use lots of Javascript or server-side voodoo coding to get overflowing text to look good. With the new CSS3 feature, you can set the text-overflow property of your text to ellipsis, thus letting the browser handle this so-needed task for you.

CSS3 text-overflow: ellipsis DEMO



Dummy text. Move the slider below to change the width of this text and see how this works.

Width = 100%



The CSS Code

While this is a very simple attribute, getting this to work just the way you expect it can be somewhat tricky. All you have to keep in mind is that while the text-overflow attribute is what controls the ellipsis effect, just setting this one attribute by itself isn't enough.
<style>
.elip { 
  text-overflow: ellipsis;
  overflow: hidden; 
  white-space: nowrap; 
  width: 100%; 
}
</style>

<p class="elip">Some text to be wrapped by the CSS3 ellipsis attribute<p>

Notice that along with the text-overflow, you also need to make sure you specify two other properties: white-space (keeping the text from wrapping into multiple lines), and overflow (which keeps the text from bleeding through its container).

Other than that, this is pretty simple. Try out different ways to use this and see how it works for yourself. One thing I did notice is that if you use this property with a big paragraph that takes up multiple lines, instead of only applying the ellipsis to the last word or whatever, every line that has a break (either through a br tag or a new paragraph) will be ellipsed. Lines of text that expand beyond the one line will not wrap (due to the white-space property). So I think this will be for useful in situations where the ellipsis is applied to a header or title type text. Anything beyond a line (such as a summary) might not work so well, or at least I haven't figured out how to make it work right with a block of text. But that's CSS3 for you... enjoy!

Sunday, June 26

How to run Python CGI in WAMP


I've had a few people ask me how to install Python in WAMP (Windows Apache MySQL and PHP), so here's a quick tutorial on how to set that up on your WAMP server. What I'll do is assume you already have both WAMP and Python installed, explain how to run your Python .py scripts through WAMP, then I'll have a quick tutorial explaining how to download and install both Python and WAMP individually.

Writing your first Python cgi script


Before you can run your Python scripts on the browsers, you'll need to write a .py script. Here's a quick one just to illustrate the point. Type this in Notepad and save the file as hello.py:

#!python

print "Content-type: text/html"
print ""

print "Hello, World"


Now click the WAMP icon on your system tray, find the Apache option, then select the modules option. Make sure there's a check mark next to cgi_module. If there isn't a check mark next to cgi_module, go ahead and click it. This will enable the module and restart your WAMP Apache server. Now, go back to Notepad and save your hello.py file in the right cgi-bin directory. The precise path to this folder is probably different on each system, but is found inside the WAMP directory, then inside the bin directory, inside Apache. On my system, the path to the cgi-bin directory is

C:\wamp\bin\apache\Apache2.2.17\cgi-bin


Once your Python script file is saved, go to your browser and access the script by going to

http://localhost/cgi-bin/hello.py



That's it. No need to install extra modules or a whole different server altogether. Now to a brief tutorial on installing WAMP and Python on Windows.

How to install WAMP


In this tutorial I'll assume you already have WAMP downloaded and installed. If you don't, click the link above and download the WAMP server. Installing it is really simple (click and follow the prompts), but I'll save the details to another tutorial if the need for it arrises.

How to install Python on Windows

Once you have WAMP installed, the next thing you'll need to do is to install Python. Again, this should be pretty straight forward. Click the buttons and follow the few prompts. Once the installation concludes, you should be able to open a terminal (DOS) window and verify that the installation was successful. Try typing the following command in DOS:

python


If you see a response that says something like Python 2.7.2 (or whatever version you installed), then the installation was successful. If this is the case, you'll see the three >>> indicating that you can start typing Python code and run it right there. If, on the other hand, you get an error message from Windows, then this means you'll need to set up a system variable with the path to your Python install. This is really simple:

How to set up Python environment variable Path on Windows


What you'll do is tell Windows to run a program called python.exe located at a certain directory whenever Windows get a request to run python. To do this, open up your Control Panel and run a search on that window for environment. Windows XP and up (Vista and Windows 7) will bring up a link that says Edit the System Environment Variables. Click that, then click the button that's labeled Environment Variables...

Next, open up a Windows Explorer window and go to the location where you have installed Python. As this could be different for different folks, you'll just have to find where you installed your own. On my home system, I installed Python at

C:\Python


Once you have located your main Python folder, copy the folder path and go back to the Environment Variables window. Under System variables, find the one that's labeled Path, select it, and click Edit. Now go to the Variable value field, and be sure you don't erase anything from this field. Simply go to the end of the field, place a semicolon at the end of the list, and paste the path to your main Python folder. Click OK to save this, and you're done! Now you can open up a DOS window and type in Python, and start coding to your heart's content.

Tuesday, March 22

jQuery Slideshow - HTTP Efficient

Why another jQuery Slideshow Tutorial ?



A while ago I posted a tutorial on a Javascript slideshow implemented in Prototype. That was all nice and well, since there weren't a whole lot of Prototype tutorials out there. But also, the specific implementation I did was especially powerful because it had HTTP requests in mind. So now we have a version of that same slideshow in jQuery.

Live Demo:








Here's the logic behind my slideshow is simple


The usual slideshow requires that you list all of the images you want sliding in some sort of list. Then the images, through CSS, are all stacked on top of each other so only the top-most image is visible. Then, every so often the top image fades out, revealing the next one. My issue with this approach is that, suppose you have 10 images in the slideshow, all 10 images are downloaded (10 HTTP requests, bandwidth, latency, etc). Worse yet, what if the user only stays on the page long enough that only the first two images are shown?! You wasted bandwidth and loading time for the other 8 images. Not to mention if you want 100 images in the slideshow...

My approach:


I only list two images at a time. One is the top-most image (the one that's visible), and the one immediately behind it. Then, when the timer fires (the image slides), I fade the top image, reveal the back image, and wait for the next timer event to fire. When the timer gets ready to fire again, I download the next image, place it behind the current top-most image, and repeat the process. Now if the user only views my site long enough that 5 images are rotated through the slideshow, I don't have to download the remaining 95 images I wanted to display.

The Code



As this slideshow is using jQuery, the first thing we do is import the jQuery library:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>



Now we define the basic CSS so the images are self-contained:

The CSS

<style>
#iSlideShell { position: relative; height: 175px; width: 500px; overflow:hidden; }
#iSlideShell img { position: absolute; }
</style>

* note that the CSS above sets the height and width of the slideshow container, but those can be customized to your own needs.



Then we set up the HTML where the images will be displayed:

The HTML

<div id="iSlideShell">
<img id="back-image" src="image1.jpg"/>
<img id="front-image" src="image2.jpg"/>
</div>



It's very important that you keep the ID attributes of those three HTML tags as they are. If you do decide to change them, change them also in the following Javascript.

The Javascript

// keeps track of what image to display next
var i = 0;

// the time each image will display before it fades out
var delay = 3000;

// the time it will take to fade each image
var fadeDelay = 150;

// the filename for each image. Don't include the .jpg extension
var iSlides = new Array("image1", "image2", "image3", "image4", "image5");

// This is where the magic happens
function rigoSlide()
{
// show the top image
$('#front-image').show();

// make the bottom image visible
$('#back-image').show();

// after the image finishes fading, bring the back image to the front
$('#front-image').fadeOut(fadeDelay, function(){
$('#front-image').attr('src', $('#back-image').attr('src'));
});

// increment the array index, but never go beyond the array boundaries
i = (i + 1) % iSlides.length;

// now load the next image behind the image currently showing
$('#back-image').attr('src', iSlides[i] + ".jpg");

// start process over again...
setTimeout(rigoSlide, delay);

}


// call the slideshow when the page finishes loading
$(document).ready(function(){ rigoSlide(); });



Cut and Paste



Now, I realize some of you might not be able to put the above steps together all by yourself... so if that applies to you, just go ahead and paste the following block of code in your website where you want the slideshow to appear. Just make sure to replace the bold text with the names of the actual images you'll be using for your own slideshow:

<div id="jq_rigo_slide" style="width:994px; height: 300px; position: relative; top: 0; left: 0; margin: 0; padding: 0; overflow: hidden;">
<img id="jq_b" src="img1" style="position: absolute; display: block;" />
<img id="jq_f" src="img2" style="position: absolute; display: block;" />
</div>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js' type='text/javascript'></script>
<script type="text/javascript">
var i = 0;
var delay = 3000;
var fadeDelay = 150;
var iSlides = new Array("img1", "img2", "img3", "img4", "img5");

function rigoSlide()
{
$('#jq_f').show();
$('#jq_b').show();
$('#jq_f').fadeOut(fadeDelay, function(){
$('#jq_f').attr('src', $('#jq_b').attr('src'));
});
i = (i + 1) % iSlides.length;
$('#jq_b').attr('src', iSlides[i] + ".jpg");
setTimeout(rigoSlide, delay);
}
rigoSlide();
</script>



Conclusion


So there you have it. I'd recommend you save the Javascript externally and include it the same way you're including the jQuery Library, but that's not required for this to work.

Post your questions, comments, or concerns below.

Thanks,

Sunday, January 2

Weird CSS3 Demo & Tutorial


Below is a form with some weird CSS3 effects that you may not know about. But keep in mind this one principle I've learned earlier in my career, and it has served me very, very well:


Just because you can, doesn't mean you should


Just because something in possible, don't be in a hurry to use it or do it. Keyword here is: HTML Marquee and Blink tags


CSS3 Demo Form

Enter your name:
Enter your e-mail:
Enter your phone number:

CSS3 » Outline


The outline attribute is like a border, but is drawn outside the actual border of the element. According to the W3Schools, the purpose of this property is to make an element "stand out". You may have noticed this in Chrome. I personally find it annoying because in Chrome, when you enter an input element (in a form), Chrome draws a yellow line around the box (input box). This is the outline property kicking in.


You can set the outline just like you do a border:


outline: 1px solid #c00


or you can turn it off by either setting it to 0 or none:


outline: 0;
outline: none;


If you look at the source code in Google's main page, they use both the number zero and the value 'none' when setting the outline of elements to nothing.


CSS3 » Zoom


The zoom attribute is a dangerous property, because some people think it's so cool, and therefore they over use it in horrible ways. Basically this works similar to how your browser would zoom in and out of your page when you use the magnification features in it. If you set an object's zoom to 100% (or 1.0), then it will look 'normal'. However, if you set it to something greater than that, the object will scale like it would when you zoom in it. Pretty self explanatory.


Some people used to add hovering effects by changing the text's font-size for the hovered state, but now you can set its zoom to something and affect not only text and the box around it, but also images! This is that terrible two-wedge sword. Could be a great help, or a sure way to flood the web with ugly zooming effects:



.link { font-size: 1.25em; }
.link:hover { zoom: 200%; }


CSS3 » Transformation


The transformation attribute is part of the webkit library. You can use it in Mozilla Firefox using they -moz counterpart. What a lot of people are doing is setting the same property they set to -webkit (which works fine in Google Chrome and Safari browsers, as well as the iPhone, iPod touch, iPad, and the Android systems) set it to -moz, -o (for Opera), -ie (Internet Explorer), and then just list the property with no prefix for the day it becomes a standard. I don't necessarily recommend this, especially if the library you're specifying doesn't support the property (like -ie-transition), but it doesn't hurt. Besides, if a lot of people are doing it, you might not look like a fool doing it too...


To use transformations, you specify the transformation desired, the value, and a unit to go along with it:


-webkit-transformation: rotate(-25deg);


CSS3 » Transition


Finally, transitions are awesome things that happen between the beginning and the end of an attribute change. For instance, when you set a font color, then a different font color for that same text when it get hovered, then you only see the first color, then the end color when teh text is hovered. With transitions (also part of -webkit), you can specify what happens during that change. If you've ever worked with Flash, this should be natural. With CSS3 you specify how slow that transition happens. In the form example above, I specified the transition to take half a second:


-webkit-transition: all 0.5s linear;


Here I was a bit lazy because I didn't want to specify a transition speed for zoom and rotate, so I used the keyword 'all'. the keyword 'linear' specifies how that transition takes place. Other acceptable values include:

  • linear - constant speed
  • ease - gradual slowdown
  • ease-in - speed up
  • ease-out - slow down
  • ease-in-out -speed up then slow down

So there you have it. I hope this helps, but please, use these things for the good of the web =)


Feel free to post any questions you may have or email me directly.


Monday, October 11

Java Applet Tutorial

How to create a Java Online Game

Overview


In this simple introductory Java Applet tutorial, we’ll build a straightforward Super Mario Brother online. We’ll actually just animate Luigi running around the screen and responding to user input. The controls will be very basic: move Luigi using the left and right arrow keys (← to move him to the left, and → to move him to the right), and change the speed at which he moves by pressing the up and down keys. The controls are shown on the screen and are indicated by the "thread break" marker.

For a quick demo of the final product, checkout the box below:



Also, be sure to grab some sprite images for your game:

Super Luigi Brother Online Frame 0,1Super Luigi Brother Online Frame 0,2Super Luigi Brother Online Frame 0,3Super Luigi Brother Online Frame 0,4Super Luigi Brother Online
Super Luigi Brother Online Frame 1,0Super Luigi Brother Online Frame 1,1Super Luigi Brother Online Frame 1,2Super Luigi Brother Online Frame 1,3Super Luigi Brother Online Frame 1,4


The Set Up: Intro to Java Applets

Probably the first thing you’ll notice about Java Applets is the fact that they don’t have a main() method like all other Java programs do. Instead, Java Applets will have an init() method, which must be a public, void returning method (similar to the standard main).
Also, Java applets are meant to be viewed through a browser, so be sure to create an HTML file to run your app in. I will show you how to do that when we get to that point.
Finally, I will show you the libraries we’ll be working with, and therefore will need to import.

The Java.Applet Library

In order to create our demo applet, go ahead and import the following libraries to your Luigi.java file. This will be the file we’ll build for this tutorial.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;


Those libraries take care of making our applet, loading files from a web server, and listening and responding to user input events.

Sprite Animation in Java

In order to simplify this tutorial, and yet make this code somewhat more portable and expandable, let’s create a class that will handle the individual sprite animations that we’ll use. Actually, let’s create a class to represent Luigi, who will be our hero in this case. This class will basically have the following member variables:

private int x; // Luigi’s on screen x-coordinate
private int y; // Luigi’s on screen y-coordinate
private int dtX; // The delta-x; the amount of units to move Luigi horizontally each time he moves
private int pos; // To keep track of when Luigi moves outside the screen
private String name; // Represents the name of our character
private boolean K_RIGHT; // Is the user pressing the right key
private boolean K_LEFT; // Is the user pressing the left key
Image[] src; // An array to keep all the sprite images used in the game


That’s pretty simple stuff. We can initialize those variables right on our constructor. I’ve found it helpful to offer at least a couple of choices to the programmer using your code, so in this tutorial, we’ll create two constructors for this Sprite class: one with parameters to initialize a Sprite object (a character for your game), and one that takes no parameters. This second constructor will actually just call the first-mentioned constructor with some default values. This way we have two methods doing the same thing, but not duplicating hardly any code at all. So here are the constructors:

public Sprite(String pName, int pX, int pY)
{
name = pName;
x = pX;
y = pY;
dtX = 10;
pos = 0;
src = new Image[8];
K_RIGHT = false;
K_LEFT = false;
}

public Sprite()
{
this("Tupac", 10, 10); // The name and starting position of our default character
}


And in order to keep this class simple, yet functional, let’s add a few methods:

public int x() // returns the x position of your character
public int y() // returns the y position of your character
public void walk(String dir) // moves your character horizontally
public void stand(String dir) // changes the character’s sprite image if he’s not moving
public int pos() // returns the x position of the character
public boolean K_LEFT() // tell us if the user is pressing the right key
public boolean K_RIGHT() // tell us if the user is pressing the right key
public void setKey(String dir, boolean state) // respond to the user pressing the right or left key


You will notice that our Sprite class could have used less methods, had only the member states been more accessible. It is good practice, however, to restrict member states as much as reasonably possible, and create good ol’ getters and setters. Yes, the Java likes programmers that use a getter and setter whenever possible.

Sprite Class Code

Most methods should be pretty self-explanatory and easy to follow… For the most part we just check for the current state of our character, increment his x-position by a uniform amount (determined by delta-X), and make sure he is never displayed outside the screen boundaries.

class Sprite
{
private int x;
private int y;
private int dtX;
private int pos;
private String name;
private boolean K_RIGHT;
private boolean K_LEFT;
Image[] src;

public Sprite(String pName, int pX, int pY)
{
name = pName;
x = pX;
y = pY;
dtX = 10;
pos = 0;
src = new Image[8];
K_RIGHT = false;
K_LEFT = false;
}

public Sprite()
{
this("Tupac", 10, 10);
}

public int x()
{
return x;
}

public int y()
{
return y;
}

public void walk(String dir)
{
if (dir == "left")
{
x -= dtX;
if (pos < pos =" 5;"> 7)
pos = 5;

if (x < -50) x = 450; } else if (dir == "right") { x += dtX; if (pos > 3)
pos = 1;
if (pos <> 3)
pos = 1;

if (x > 450)
x = -50;
}
}

public void stand(String dir)
{
if (dir == "left")
{
pos = 4;
}
else if (dir == "right")
{
pos = 0;
}
}

public int pos()
{
return pos;
}

public boolean K_LEFT()
{
return K_LEFT;
}

public boolean K_RIGHT()
{
return K_RIGHT;
}

public void setKey(String dir, boolean state)
{
if (dir == "right")
K_RIGHT = state;
if (dir == "left")
K_LEFT = state;
}
}



Java Applet’s Main()
As mentioned earlier, the method main() is not used in applets like in regular java apps. Here we use the method init(). In our case, we’ll be extending the class Applet (all applets will), and we’ll implement the following classes and interfaces: ActionListener (for general event listening), KeyListener (for specific keyboard events), and Runnable (to create threads!).
Once inside your main game class, just do what you would in any other class, but keep in mind that the program will enter in through init(). In this tutorial, we’ll create the following state variables:

final static int WIDTH = 500; // the width of our screen area
final static int HEIGHT = 200; // the height of our screen area
private int FPS; // not really the framerate, just a way to keep the animation constant
private String TSE; // phrase to display if we get an Interrupted Exception while trying to put our animation thread to sleep for FPS milliseconds
Thread runner; // where we’ll keep Luigi
Image image; // this is how we’ll add a double buffer to our app
Graphics graphics; // this is also part of the double buffer method we’re using.
Sprite hero; // the manifestation of our Sprite class


As far as the methods we’ll use to control our awesome Super Mario Brother Online game, featuring Luigi, we’ll keep it simple. Most methods are defined because we’re implementing interfaces that require us to define them, even if we make them blank. This is a key feature of the Java Language. Be sure to understand Java’s polymorphism, inheritance, interfaces, and abstract classes if this confuses you. In case you don’t know what any of that means, it might sound like a lot of new stuff to learn, but really, it’s just one single concept, which is not really very complicated to understand. But it is very fundamental that you at least have a general idea about those topics if you want to become a decent Java Game Programmer…

public void paint(final Graphics g)
public void actionPerformed(ActionEvent e)
public void keyTyped(KeyEvent key) {}
public void keyReleased(KeyEvent key) {
public void keyPressed(KeyEvent key)
public void start()
public void stop()
public void run()
public void update(Graphics g)


The main meat of the code takes place inside the run method of our runner thread. You can think of this as the Luigi thread. Basically, we check for the current state of the app. If the user is pressing a key, for example, that will be a different state than the app would be in if no keys were being pressed at the time the thread performs this checks. The thread basically checks for those states constantly… If the right or left key is in fact being pressed, he call Luigi’s move method and moving to the right or left based on the app state. We then tell the app to refresh the screen images, and we tell the thread (just Luigi’s thread) to sleep() for a brief amount of time. If we don’t do this crucial step, the thread will run as fast as it can. This would mean the thread would run faster/slower depending on the computer running the app. Adding the call to sleep() makes our app constant across different computers.

In case you don’t know much about threads, what happens is that our app will do various things in different threads, but all at the same time. It would be weird to check first if there are keys being pressed, then if so, tell Luigi to move, then redraw his image on the screen, then make sure he’s not outside the screen, etc… through threads we can check on a key being pressed on the keyboard, while at the same time we can be redrawing the screen, and at the same time we can be performing a calculating to see where Luigi is positioned.

public class Luigi extends Applet implements ActionListener, KeyListener, Runnable
{
/**
*
*/
private static final long serialVersionUID = 1L;

final static int WIDTH = 500;
final static int HEIGHT = 200;
private int FPS;
private String TSE;
Thread runner;
Image image;
Graphics graphics;
Sprite hero;

public void init()
{
image = createImage(WIDTH, HEIGHT);
graphics = image.getGraphics();
FPS = 100;

resize(WIDTH, HEIGHT);
hero = new Sprite("Luigi", 20, 50);

addKeyListener(this);

setLayout(new FlowLayout());
setBackground(Color.white);

/***
* Here we’re loading the images from a sub-directory called "luigi_img" where the images are stored. Since we’re using the java.net library, we can actually load the images straight from a web server (like "http://www.rodrigo-silveira.com/dharma/cs246/img/luigi.png").
*
***/
hero.src[0] = getImage(getDocumentBase(), "luigi_img/luigi,0r.gif");
hero.src[1] = getImage(getDocumentBase(), "luigi_img/luigi,1r.gif");
hero.src[3] = getImage(getDocumentBase(), "luigi_img/luigi,2r.gif");
hero.src[2] = getImage(getDocumentBase(), "luigi_img/luigi,3r.gif");
hero.src[4] = getImage(getDocumentBase(), "luigi_img/luigi,0l.gif");
hero.src[5] = getImage(getDocumentBase(), "luigi_img/luigi,1l.gif");
hero.src[7] = getImage(getDocumentBase(), "luigi_img/luigi,2l.gif");
hero.src[6] = getImage(getDocumentBase(), "luigi_img/luigi,3l.gif");
}

public void paint(final Graphics g)
{
update(g);
}

public void actionPerformed(ActionEvent e)
{
repaint();
}

public void keyTyped(KeyEvent key) {}
public void keyReleased(KeyEvent key) {
if (key.getKeyCode() == KeyEvent.VK_RIGHT)
{
hero.setKey("right", false);
hero.stand("right");
}
else if (key.getKeyCode() == KeyEvent.VK_LEFT)
{
hero.setKey("left", false);
hero.stand("left");
}

else if (key.getKeyCode() == KeyEvent.VK_UP)
{
FPS++;
}
else if (key.getKeyCode() == KeyEvent.VK_DOWN)
{
FPS--;
}
}

public void keyPressed(KeyEvent key)
{
if (key.getKeyCode() == KeyEvent.VK_RIGHT)
{
hero.setKey("left", false);
hero.setKey("right", true);
}
else if (key.getKeyCode() == KeyEvent.VK_LEFT)
{
hero.setKey("right", false);
hero.setKey("left", true);
}
repaint();
}

public void start()
{
if (runner == null)
{
runner = new Thread(this);
runner.start();
}
}

public void stop(){}

public void run()
{
while (runner != null)
{
repaint();

try
{
Thread.sleep(FPS);
if (hero.K_LEFT())
{
hero.walk("left");
}
else if (hero.K_RIGHT())
{
hero.walk("right");
}
}
catch(InterruptedException e)
{
TSE = "Exception caught while trying to put thread to sleep...";
}
}
}

public void update(Graphics g)
{
g.drawImage(image, 0, 0, this);
g.drawImage(hero.src[hero.pos()],hero.x(),hero.y(),this);

g.setColor(Color.red);
g.drawString("Luigi (" + hero.x() + ", " + hero.y() + ")", 10, 10);
g.setColor(Color.black);
g.drawString("Thread break = " + FPS, 10, 25);

// Display errors
if (TSE != null)
g.drawString("Thread Sleep Error: " + TSE, 10, 40);
}
}

Conclusion

While this Java Applet tutorial was almost overly simplistic, the concepts we covered are pretty important. In case you don’t quite understand the way threads work, or how we can implement interfaces in Java, this would be a recommended subject to learn next. If you did follow the code without much confusion, then the challenge would be for you to try to improve on it. You will notice that by pressing the up/down arrow keys you can dynamically change the value of FPS, which will tell the thread to do what it does more times per second. Right now the FPS speed controls both the animation speed (how fast we change the image frames), and how fast Luigi moves. Can you think of a better way to do this? What if we want to move Luigi faster, but keep the animation as smooth? Try implementing different things, but be sure to check back soon for my follow up tutorial, where we’ll be adding more physics to Luigi. We’ll make him slide (like if he is running on ice), and jump. We’ll also add some background imagery to make the level prettier to look at.

Monday, August 30

JS Prototype Tutorial

5 Ways to Speed up Javascript



One big problem the entire internet suffered from when Macromedia Flash became popular, was that people were overusing this new exciting technology, and the overall performance of their site was far too poor. Sadly, we are starting to see a similar pattern as Javascript libraries like Prototype, JQuery, MooTools, Scriptaculous, etc. Sites are looking great, but the effects, though relatively light-weight, are getting cluttered, which slow down the page load, and the results are at times counter-productive.

In this JS tutorial, we’ll talk about a needed subject, which will benefit both the site owner and users. This subject is Javascript Speed up techniques.

1. External File Cache


The first thing I have seen many programmers take for granted is the browser’s ability to cache code for them. Caching code has many benefits that some people don’t realize. For one thing, if you store your Javascript on your user’s machine, you don’t have to download it every time the user requests it. If the user doesn’t have to download something, the page load will be faster – obvious. The down side of this could be the fact that if you change the code too often, then the Javascript your user has cached will be different. This is especially bad if the cached js has bugs in it, and the new code you deploy is a patch to it.

Overall, caching your Javascript is a best-practice to be observed. The way you cache your scripts is to store it in an external file and link it in to your main HTML file by using the following syntax:

<script type="text/javascript" src="file-name.js"></script>


Make sure you place this line of code inside the head of your HTML document. If this code is not placed within your <head> and </head> tags, the document will not validate with the W3C. This takes us to the next tip to help you speed up your javascript.

2. Code Placement


Some people have suggested that a good way to speed up your code is to place it at the end of your HTML document. This makes some sense, and can be confusing since Google specifically instructs webmasters to place the Google Analytics code just before the closing </body> tag. The reasoning behind adding Javascript to the end of your file is that everything else (images, CSS, text, etc.) can load first, so while the js script is loading, the user can still see everything else on the page (the main reason they visit your site for). However, placing the code at the end of your file won’t allow you to cache the file.

The solution is to add the code to the <head> portion of your file through an external file. If the script loading interrupts the rest of the page load, you may need to change your design structure. Abstracting your code into classes and functions will keep the code from loading unless you tell it to. Any code that you do need loaded automatically can be called on your document’s onload event. This way the code will be loaded only after the rest of the file is loaded, and it will still be cached. In libraries like Prototype or JQuery, you can use the document.ready() function.

3. Reduce HTTP Requests


A simple analysis of a regular page load reveals that most of the loading time of a web page is spent sending and receiving HTTP requests to and from the server. The immediate solution to this, simply enough, is to reduce the number of requests you make to your server. One way to do this with your Javascript is to include all of your js code on a single file (so only one HTTP request is necessary to load it), then cache the file so it doesn’t need to be downloaded again. In CSS, as a side note, a common technique is called Image Spriting, where all of the images referenced in your CSS are combined into one single, larger image file, so only one HTTP request is necessary to pull all those images from the server.

4. Inline your functions


A tedious, yet masterful habit to pick up is to have two versions of your scripts. One version is well commented, well designed and coded, and carefully structured, while the other version – the version you deploy, is highly optimized. This will be covered more in-depth in the next section, but in short, a main way to speed up your js is to avoid the overhead involved in calling functions. The easiest way to accomplish this is to inline each and every function call in your code. Javascript doesn’t have an “inline” function definition like C++, so the way you do this is to physically paste the entire function every time it is called. This will greatly speed up your code execution.

5. Compress your Code


Finally, after you optimize your code and inline your functions, the final thing to do to get the most out of your script, is to compress your code. Some people prefer to obfuscate their code to discourage people to straight copy their own code. Google offers a great tool known as the
Closure Compiler, which compiles your Javascript code into very compact, optimized code. This extra step definitely takes extra work, but is an absolute must have for anyone wanting to speed up their javascript libraries.



Saturday, August 21

Home is Where Your Destiny is

The sun still laid low behind the rising mountains. The thin, cold rain bathed his car as he sat in silence driving southward. The flat road vanished to a far away point straight in front of him, leveled with his eyes. In his mind's eye the memories were vivid and fresh, and the time that had passed since he'd last been home seemed to be less than it really had. After his many travels, the traveler was anxious to be back, and curious to see his dear family again. The stores he'd heard over the years told him of little change, and the traveler wondered what he'd find. Through the many layers of uncertainty, insecurity, and the fear of disappointing his family, deep inside, the traveler was glad to be coming home.

As he entered the small town of Kibou, Tabi, as he was known as a child, noticed how much things had remain the same. There were new additions to the town, of course, such as the two-story Walmart that could be seen from the distance, a new IMax theater was built to entertain the mind, high buildings sophisticated the market place, an international airport facilitated transportation, and the few middle schools, high schools, and the community college had been rebuilt in order to accomodate the eager seekers of knowledge. As Tabi looked around him, it was clear that Kibou had merely kept up with times.

The street where his parents lived had seen busy days before. Weekend gatherings were common place back in the day. Today was no exception. Pound after pound of fresh-cut meat was leveled against the grill, the children ran around the Haytae backyard, the women sat around wearing their sun dress talking about the latest topics that went around town, while the men spoke of recent sporting outcomes, business events, and other such subjects.

Tuesday, April 13

How to JavaScript: Prototype Slideshow Tutorial

Javascript Slideshow: A Web 2.0 Tutorial (a prototype tutorial)




Here's a quick Prototype tutorial for those looking for a simple javascript slideshow. This is not intended to be a JQuery discussion or tutorial, but a quick prototype tutorial. The desired result is an efficient, useful javascript slideshow coded in prototype js.

Before we get started, be sure to download the external Prototype files. In this amazing web 2.0 tutorial we'll use the effects.js and prototype.js files. In addition to this prototype tutorial, visit the official site of Prototype or learn more about Javascript .

Demo

For a quick demo on what the final product of this prototype tutorial is to look like, please refer to the header of this very blog (Rodrixar). Image changes after 3.5 seconds.

1. The goal

Our goal in this prototype tutorial is to come up with a javascript slideshow. The way it will work is that you'll have one image displaying, then after a predetermined amount of time (4 seconds in my example) the image will fade out and a different image will be showing behind it, and after another 4 seconds that image will fade out and a new one will display behind it. Then when the last image fades out, the first image will display.

The code design will be as follows:

  • An array will hold the filename for each image to be displayed
  • There will be 2 image elements on screen at all times, both stacked atop each other
  • A timer will call our main function every 4 seconds
  • This function perform the following tasks:
    1. Fade the top image so the image behind it will display
    2. After the fading effect is done, the front image will be the same as the back image (his step will be invisible to the human eye)
    3. Then the back image will be assigned a different value (it will display the next image in the array)
    4. Lastly, we'll check if we've hit the end of the array. If so have, we'll be sure the back image displays the first image of the array so the loop continues forever and ever (or until the person viewing your slideshow clicks away from your page)
  • The function will set the timer to come back in another 4 seconds

2. The setup

First thing we'll do is set up the HTML file. Though this is a prototype tutorial and a web 2.0 tutorial, I'll assume you could use the extra explanation. So open up your favorite text editor and be sure to have the following lines of code:


<html>
<head>

<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript" src="effects.js"></script>

<script type="text/javascript">

</script>

<style type="text/css">
#iSlideShell { width: 250px; height: 250px; position: relative; }
#iSlideShell img { position: absolute; }
</style>

</head>

<body>

<div id="iSlideShell">
<img id="iSlideBack" src="img1.jpg"/>
<img id="iSlideFront" src="img1.jpg"/>
</div>

</body>
</html>

This is our basic HTML setup. Be sure the external javascript files are referenced right (that the link points to the right directory where you have the files saved). Also, be sure the the images in the <img> tags point to first 2 images you'd like displayed. Note that the top image (the one that will show first) is the one in the second <img> tag (since they're stacked through the css position absolute command). Make sure also that the <div> has the same height and width as the images in your slideshow. If the images you use aren't the same dimension we'll need to make a few slight adjustments to the <div> but this won't be covered in this prototype tutorial.

Now we'll set up the images we'll be using in our slideshow.

3. The Javascript

Inside the Javascript tags in the HTML code we'll set up the following variables:

var i = 0;
var iSlides = new Array("img1", "img2", "img3", "img4", "img5");

These will be our variables. The i will keep track of where we are as we loop through the array (iSlides), which is a list of all the images we want to display. Note that you don't include the file extension in the array, but only the filename. For this javascript tutorial you will need to use images of the same file type.


Next we'll add our function, which I'll call iAnimate. I'm not sure why I have the tendency of adding the letter "i" to the front of my variables and function. Maybe it's because iLike it :)

function r$(id) { return document.getElementById(id); }

function iAnimate()
{

r$('iSlideFront').show();
r$('iSlideBack').show();
r$('iSlideFront').fade();
r$("iSlideFront").src = r$("iSlideBack").src;

i == (iSlides.length - 1) ? i = 0 : i++;
r$("iSlideBack").src = "img/" + iSlides[i] + ".jpg";

setTimeout('iAnimate()', 4000);
}

window.onload = iAnimate;

The function "r$" may look like Prototype and/or JQuery, but all it is is a shortcut function I created so I don't have to type "document.getElementById()" over and over...

The first thing the function does is be sure both images are showing. In Prototype (and in JQuery), when you "hide" or "fade" (or "fadeOut") and element, that elements changes opacity gradually and finally has its css attribute "display" set to "none". By calling the show() function, we make sure the display for both images is set to "block". Once that's done, we fade the front image.

Then we make sure the front image is the same as the back image. This may seem pointless the very first time the function is called, since no visible change takes place, but once the first image fades, this is important.

The next step is to find out what the next image is in the array, and assign that to the back image. The conditional statements ? : checks if the variable i is equal to the total amount of images in the array minus 1. The reason it's (length - 1) is because the first image in the array is represented by iSlides[0] (zero is the first element in an array in Javascript). If this statement returns true, that means we've displayed the last image in the array, so now we must display the first one. That's when the assignment i = 0 gets called. If the statement returns false, we increment i by 1.

The back image (iSlideBackthen gets assigned the next image of the array, and the timer is set to explode in 4000 milliseconds, or 4 whole seconds. Once those 4 seconds are counted by the computer's clock, iAnimate() is called again, and the fun starts all over!

4. Conclusion

This is all there is to it. My goal was to make this as simple as possible, but making this javascript slideshow more robust shouldn't be too difficult with some basic understanding of javascript, prototype, html, or css.

One of the main benefits the code provided in this javascript slideshow (other than, but because of its simplicity) is the fact that the only images loaded are the ones currently displayed. Most prototype tutorials and JQuery tutorials I've seen load all images as the page loads (longer loading times), then they do what they must. In this javascript slideshow, if the user leaves the page after only 3 images have loaded, that's all the loading the code will do. This will save you resources and loading time.

Any questions, feel free to post in this prototype tutorial.

5. The Code

Here's the complete code for those of you reading my prototype tutorial that are mindful of the mileage on your mouse and your daily keystroke allowance:

<html>
<head>

<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript" src="effects.js"></script>

<script type="text/javascript">
var i = 0;
var iSlides = new Array("img1", "img2", "img3", "img4", "img5");

function r$(id) { return document.getElementById(id); }

function iAnimate()
{
r$('iSlideFront').show();
r$('iSlideBack').show();
r$('iSlideFront').fade();
r$("iSlideFront").src = r$("iSlideBack").src;

i == (iSlides.length - 1) ? i = 0 : i++;
r$("iSlideBack").src = "img/" + iSlides[i] + ".jpg";

setTimeout('iAnimate()', 4000);
}

window.onload = iAnimate;
</script>

<style type="text/css">
#iSlideShell { width: 250px; height: 250px; position: relative; }
#iSlideShell img { position: absolute; }
</style>

</head>

<body>

<div id="iSlideShell">
<img id="iSlideBack" src="img1.jpg"/>
<img id="iSlideFront" src="img1.jpg"/>
</div>

</body>
</html>

Prototype Tutorial

Friday, April 9

Chinese Proverbs & Chinese Sayings

Chinese Proverbs



A lot of people have been asking me why I haven't posted ancient Chinese proverbs lately, especailly after posting about the journey of a thousand miles . So here are some of my favorite Chinese proverbs.

A bird does not sing because it has an answer; but because it has a song


My thoughts on it can be answered with the not-so-popular,

Not everything that's doable is worth doing; but whatever is done must be done well


Actually, I made up this and other nice proverbs from other Chinese proverbs. Nevertheless, let us not forget that,

He who cannot but does is better than he who can but won't


At the beginning of a new phase in my life, I take comfort in knowing that,

A journey of a thousand miles must begin with a single step


It was pointed out last week that because a journey of a thousand miles does begin with the first step, we must watch our step! Remember also that

When ten hours is given you to cut down a tree, spend the first eight sharpening your ax.


Again, not from real Chinese Proverbs, but a good thought nontheless. On a more realistic note, since this collection of Chinese Proverbs is so popular, let me post a few legit Chinese Proverbs:
  • When you drink the water, remember the spring

  • Keep your broken arm inside your sleeve

  • He who strikes the first blow admits he's lost the argument

  • Do not remove a fly from your friend's forehead with a hatchet

  • If you don't want anyone to know, don't do it

  • An ant may well destroy a whole dam

  • Don't use a cannon to kill a mosquito

  • Dismantle the bridge shortly after crossing it

  • Dream different dreams while on the same bed

  • Do not employ handsome servants

  • Crows everywhere are equally black

  • To believe in one's dreams is to spend all of one's life asleep

  • He who treads softly goes far



The journey is the reward


In sharing Chinese Proverbs I like the philosophy they help us keep in perspective. A wise student of Chinese proverbs ponders them but remembers them. Here are a few that I've heard around the office this week:
  • Give a man a fish and you feed him for a day. Teach a man to fish and you feed him for a lifetime

  • A wise man makes his own decisions, an ignorant man follows the public opinion

  • Learning is a treasure that will follow its owner everywhere

  • A hundred men may make an encampment, but it takes a woman to make a home

  • A truly great man never puts away the simplicity of a child

  • One step at a time is good walking

  • To be uncertain is to be uncomfortable, but to be certain is to be ridiculous

  • Have a mouth as sharp as a dagger but a heart as soft as tofu

  • Once on a tiger's back, it is hard to alight

  • Shed no tears until seeing the coffin

  • Waiting for a rabbit to hit upon a tree and be killed in order to catch it

  • Only when all contribute their firewood can they build up a strong fire

Chinese Pagoda