Simple Slot machine game using HTML5 Part 1: Basics

UPDATE: See also Simple Slot machine game using HTML5 Part 2: Audio.

Here is overview on how to make simple Slot machine with HTML5. This demonstrates the basic structure of HTML5 game and how to use dynamically created graphics.

Slot machine has typically reels with images and player just initiates the action and waits until reels stop. 1 or more in single line usually determine the winning condition. In this game player wins if he or she gets more than one gold bar in row.

Here is view of the game.

Slots machine

You can try it out here

How it works

Slot machine is a single HTML page that includes the game code, webfont and jQuery. When loaded it runs SlotGame() function that initializes and runs the game.

HTML page has 3 narrow and tall HTML5 canvases, these are the reels. They are located inside div container “reels” that shows only a limited window at any time, hiding the rest of the canvases.

<div id="reels">
   <canvas id="canvas1" width="70" height="300"></canvas>;
   <canvas id="canvas2" width="70" height="300"></canvas>;
   <canvas id="canvas3" width="70" height="300"></canvas>;

On initialization, game preloads the 6 image assets. Preloading is simply done by creating Image object for each asset and listening its load event. Preloading is required, because otherwise game could not draw the reel canvases on initialization.

img = new Image()
img.src = "img/someimage.png"
img.addEventListener("load", function() {
   // image loaded

Game draws the pictures in random order on each canvas reel with shadow and slot separator bars.;
ctx.shadowColor = "rgba(0,0,0,0.5)";
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.shadowBlur = 5;
ctx.drawImage(asset.img, 3, i * SLOT_HEIGHT + IMAGE_TOP_MARGIN);
ctx.drawImage(asset.img, 3, (i + ITEM_COUNT) * SLOT_HEIGHT + IMAGE_TOP_MARGIN);
ctx.fillRect(0, i * SLOT_HEIGHT, 70, SLOT_SEPARATOR_HEIGHT);

The reels are not redrawn after this, but when moving they are simply translated with CSS3 transform downwards and when they reach threshold they are moved back to beginning. Threshold and reset offset is selected so that after the reset images are shown on same locations. This creates illusion of constantly rotating wheel. This is why images on borders are twice in the reel, so we avoid showing canvas bottom or top in any situation.
Click ‘Toggle Reels’ button on top left corner of the game page to toggle the reel visibility while it’s spinning, seeing reels in action makes explanation above much easier to understand

Here is image where reel container overflow is set to visible.


Game loop is simple, it starts when player clicks ‘Play’ and runs on every animation frame updating the reel locations based on game state and “draws” them on screen, or actually as explained earlier just translates their locations. Result is predetermined on each roll start and when each reel stop, its locked on the correct image. Update loop tries to make this when correct image is close to this location, so the jump is not too abrupt (see function _check_slot in slot.js for details).

Each browser has still different name for the transform so initialization code determines the correct CSS name and if browser has hardware accelerated 3d version.

this.vendor = 
  (/webkit/i).test(navigator.appVersion) ? '-webkit' :
  (/firefox/i).test(navigator.userAgent) ? '-moz' :
  (/msie/i).test(navigator.userAgent) ? 'ms' :
   'opera' in window ? '-o' : '';

this.cssTransform = this.vendor + '-transform';
this.has3d = ('WebKitCSSMatrix' in window &amp;&amp; 'm11' in new WebKitCSSMatrix())  
this.trnOpen       = 'translate' + (this.has3d ? '3d(' : '(');
this.trnClose      = this.has3d ? ',0)' : ')';
$('#someelement').css(this.cssTransform, this.trnOpen + '0px, ' + '-123px' + this.trnClose);</pre>

Complete code is available on Github.

Continue to Simple Slot machine game using HTML5 Part 2: Audio

32 Responses to Simple Slot machine game using HTML5 Part 1: Basics

  1. Pingback: Car Game on HTML5 | Brave New Method

  2. Pingback: Minesweeper clone in HTML5 | Brave New Method

  3. Teemu, I am currently working on a project that needs a very elementary HTML5 slot machine functionality (maybe two) very much like the basic core you have developed here. I have the functionality clearly defined and I can provide all the graphic assets. I need help making it function properly and embed it into a HTML5 interface I have built using Tumult Hype. Would you (or your group) be interested in working with me to make this happen? If you are interested, I can supply you with more details. Please let me know as soon as possible as this is in progress now with an imminent deadline. Thanks!

  4. Pingback: Simple Slot machine game using HTML5 Part 2: Audio | Brave New Method

  5. Pingback: Simple Slot machine game using HTML5 Part 3: Loading | Brave New Method

  6. Pingback: Simple Slot machine game using HTML5 Part 4: Offline mode | Brave New Method

  7. Hello, is the code free for personal/commercial use?

  8. Thank you for your example code. Our company develops casino gaming and sports solutions and we’ve recently started digging into mobile games. We’ve been able to speed up development of our 20+ slot games (we’ve done 3 reel, 5 reel and 7 reel slots) using some ideas inspired by your code – precisely the way you draw the canvas as well as the way you solved sound playback challenges.

    We’re also looking into developing video poker, blackjack, roulette and several poker games. It’s rather easy adapting this code to work with server-side logic that determines the outcome of a spin or hand.

    Thanks again. You are good.

  9. zack says:

    nice code, I was just wondering if it is set on random will there ever be a winner? Thank you.

    • tikonen says:

      Correct, when it’s set in random, win is not guaranteed. However, as the game is coded now the probability of playing e.g. 10 rounds without winning at least once is pretty low; about 1/250.

      Slot game math is all about long term return rate and not win probability.

      • zack says:

        thanks for the reply. Another question for you is there anyway to make the canvas and images loaded responsive?

      • ale says:

        Hi, i want to know how can i make a winner at least every 10 or 15 plays ? thank you

      • tikonen says:

        Have counter that you put randomly to 10 or 15 on start and or every time player wins. Decrease counter by 1 on each play, if counter is 0 set reels to random win configuration before spin.

  10. Julio says:

    Hi, Question. If you add more image into array “var items”, it can’t stop. Do you know Why?

  11. Clement says:

    Hi, many thanks for your example code. We will also draw inspiration from it for our mobile slots game, you saved us weeks of research and development, especially the way you use Canvas. Thanks again!

  12. Gamelotlabs says:

    Nice code.
    Here is a link to our HTML5 slot machine demo, using different techniques :
    You may contact if interested. Thanks.

  13. pixus says:

    Very good!
    Thank you!

  14. Lucas says:

    Hey there, great code… question, can the size of the images be changed for them to be larger?


  15. Cedric says:

    Very good post, i go custom it now and put this slot machine on my website. Thank you very much.

  16. Jon says:

    Hi, i’m looking for a slot machine game that, if the player win, gives him a password. Do you know where i can find it? I’m not a programmer

    • Sasha says:

      hey Jon.. did you ever find the slot game you were looking for? I’m looking for the same type of thing. thanks

  17. Ed Kremer says:

    Hi Teemu, thanks for the code. It is pretty insightful. Let me know if you provide consultancy services. Cheers!

  18. sonal says:

    Hi am developing a slot machine game for 5 reels but when reels stops I have to show the images result according to my REST API result how can i do that…Please help me out

    • tikonen says:

      Check the Game.prototype.restart function, you see there how it sets the results before starting the spin. You can modify this to use the values from your REST call instead of the random ones.

  19. sonal says:

    I need to replace the images which I will get in my api response after spin.Please help me on this.

  20. anjali goyal says:

    hey want to d the same in cocos2dx is there any help you can do?

  21. andre says:

    is that possible if that will auto rolling?
    and how to do it?

  22. sonbutterbee says:

    Please Help Me!!
    How to add images in column, i want to 10 –> 11++ images

  23. Fred says:

    Good article !!

Leave a Reply to Julio Cancel reply

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

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

Facebook photo

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

Connecting to %s

%d bloggers like this: