StefanZero.com

Programming the web in San Francisco

JavaScript

Building a Video Slot Machine with HTML5 Canvas and CSS3 Transitions

Introduction

When you're in Tahoe, who doesn't like stopping by the casinos and dropping a few bucks at the slots in exchange for some light entertainment and a couple of free cocktails? And sometimes, you even win!

In a couple of days, I was able to design a simple video slot machine with some JavaScript, HTML5 Canvas, and CSS3 Transitions. So let's start off with the design.

Design

The main idea is to start off with six or so cute images, and create long strips of them in random order. We'll add a "Start" button, which will trigger a CSS3 transition for each strip. Then we have to figure out if we have a winner, and then highlight the appropriate squares.

All of this is going to require exact CSS styling with a lot of tedious calculations for height, width, and positions of all the sub-elements. This would be a nightmare if we didn't use a CSS preprocessor so that we can program these specifications. However, other than a couple of nested loops for positioning the "table" for highlighting the winning squares, no complex logic is required in programming the CSS.

The most popular CSS proprocessing languages are SASS and LESS. While SASS has the greater capabilities than LESS, both languages are more than sufficient for this project. I chose LESS since we'll also be using the Twitter Bootstrap CSS3 framework, which is prepackaged as modules of LESS variables and mixins in case we require some extra customization. For this project, the choice of SASS vs. LESS is more or less an implementation detail and is not a design criteria.

The greatest part of the magic is accomplished with CSS3 transitions for moving each strip of graphics. Fortunately, this turns out to one of the easiest parts. Of course we'll be using jQuery for creating the DOM elements, adding and removing CSS classes to selected element, and attaching a single JavaScript event handlers to the "Start" button..

The program is written as a single JavaScript function and one corresponding LESS file for computing the CSS styling. To add the slot machine to any web page only requires loading these files in your HTML page, assigning a destination HTML div element, and 2 lines of JavaScript to instantiate the slots class and then initialize it.

In the class initialization, we first need to load the images, and then wait for the loading to complete before assembling the canvas strips of images. In this process, we need to store which images are stored in each position of each canvas strip, so we can later use this information to determine if we have a winner.

Procedure

This rest of this article is "in progress".

your comment

Comment Form

captcha