Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

How to build a game with HTML, CSS, and JavaScript

html tutorial game

So you want to use your basic knowledge of web development to create something a little cooler than a to-do app. Games are one of the best projects you can create, because they are very easily enjoyed by the end user and are all around fun to make! There are JavaScript libraries that are pre-made for game development , but I prefer creating from scratch so that I can understand everything completely.

The CSS and JavaScript logos.

What better game to represent web development than the Chrome dinosaur game that you play when you lose your internet connection? It’s a fun game, and it’s easy to recreate the code. It doesn’t look exactly the same, but it functions the same. If you really want, you can style it when you’re done!

To begin coding the game, create a new folder in your documents. Use your favorite text editor to open that folder, then create three new files and name them: index.html , style.css , and script.js . It’s possible to do everything in one file with HTML5, but it’s more organized to keep everything separate.

Our index.html file is going to be very simple: once you have a basic HTML layout, create a div with the ID "game" , and then two more divs inside of it with the IDs "character" and "block" . The character will be the dinosaur, and the block will be the cactuses coming towards us.

Next, go over to the CSS file and start applying styles to the two div s we just created. First, we’ll start with the game div . Select the element by its id , which is represented by the hash ( # ) symbol.

Next, we’ll style our character div. We have to declare the position  as relative because positional attributes like top and left only apply to positioned elements .

Create a keyframe animation called jump. This animation will make the top position slide up 50px and then slide back down.

Next, we’ll create a new class called animate , which applies the jump animation.

We’re going to use JavaScript to add the class "animate" to our character whenever you click your mouse.

In the script.js file, create a function called jump() that adds the "animate" class to the character div . Create an event listener that listens for the user to click , and then executes the jump function.

Create another function called removeJump()  that removes the animate class. Then add a timeout function to jump()  that runs removeJump() when the animation ends. The animation won’t run again unless we remove it.

This works, but it seems to glitch if the user clicks while it’s currently jumping. To fix that, add the line below at the beginning of jump() . It will stop the function from doing anything if the animation is running.

Now, we’ll go back to our CSS file and start styling the block div.

We haven’t created the block animation yet, so create an animation to make the block slide from the right to the left.

Now we’re able to jump, but we have to make the game end if we hit the block. Create a function called checkDead() that gets the position of the block and character, and then evaluates if they are on top of each other. If they are, then end the game.

Create a variable called characterTop that is equal to the top value of the character div. getComputedStyle() will return all of the CSS values associated with an element, and getPropertyValue()  specifies the property you want the value from.

Now, this would return a string with a value such as 100px . We only want the numerical value, so we’re going to wrap everything inside of a parseInt()  function so that it returns the value as an integer.

Create an if statement that checks if blockLeft ’s value is between -20px and 20px, and characterTop ’s value is greater than 130px. If they are, that means they’re overlapping each other and the game is over. So w’ll set an alert “Game over” .

Create an interval function  that runs the checkDead function every 10 milliseconds.

Now you have a fully functioning game. This is a great project for sharing with non-developers, because they’ll be able to better appreciate what you’ve learned!

There is a link to my GitHub if you want to copy the code. You can also check out my YouTube video if you learn better visually!

LogRocket : Debug JavaScript errors more easily by understanding the context

Debugging code is always a tedious task. But the more you understand your errors, the easier it is to fix them.

html tutorial game

Over 200k developers use LogRocket to create better digital experiences

html tutorial game

LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to see exactly what the user did that led to an error.

LogRocket records console logs, page load times, stack traces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!

Try it for free .

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • #vanilla javascript

html tutorial game

Stop guessing about your digital experience with LogRocket

Recent posts:.

Using CRDTs To Build Collaborative Rust Web Applications

Using CRDTs to build collaborative Rust web applications

CRDTs, or conflict-free replicated data types, is a concept that underlies applications facing the issue of data replication across a […]

html tutorial game

Guide to using TensorFlow in Rust

We explore the fusion of TensorFlow and Rust, delving into how we can integrate these two technologies to build and train a neural network.

html tutorial game

Using SignalDB with React: A complete guide

SignalDB enables automatic data synchronization between your components and a local in-memory or persistent database.

html tutorial game

A guide to Next.js layouts and nested layouts

Understanding how layouts, nested layouts, and custom layouts work in Next.js is crucial for building complex, user-friendly projects.

html tutorial game

9 Replies to "How to build a game with HTML, CSS, and JavaScript"

Why do you have different lines of code in your github? I`m new at programming and i`m trying to run these instructions you gave for about 2 days, i`m mixing parts of the code you have here in the page and the ones which are missing I get it from GitHub, nevertheless I didn`t succeeded in running it.

Hey it’s same as made by knife circus. Please friends check that video on YouTube. This is exact copy of that game. Not a single difference.

Knife Circus is Shawn Beaton — he wrote the post.

MY DINO ISNT JUMPING ON TOUCH HELP!!

code: var character = document.getElementById(“character”); document.addEventListener(“click”,jump); function jump(){ character.classList.add(“animate”); setTimeout(removeJump,300); //300ms = length of animation }; function removeJump(){ character.classList.remove(“animate”); }

You forgot to add if(character.classList == “animate”) {return;} after function jump(){

btw i found that you need to put

var block = document.getElementById(“block”); function checkDead(){ let characterTop = parseInt(window.getComputedStyle(character).getPropertyValue(“top”)); let blockLeft = parseInt(window.getComputedStyle(block).getPropertyValue(“left”)); if(blockLeft-20 && characterTop>=130){ alert(“Game over”); } }

setInterval(checkDead, 10);

in your .js folder not your .css

It’s very incredible and nice.

I didn’t know that it’s going to be that simple this is the first time I came to know that there are certain JavaScript libraries that are pre-made for game developments. Although they are easy to create, but these games crash a lot.

Leave a Reply Cancel reply

HTML Easy

Practical SQL course for Product Managers, Marketers, Designers, Software Engineers, CEOs and more. Learn with hundreds of bite-sized exercises which could be applied in real job right away.

How to Make a Game in HTML: A Step-by-Step Guide for Beginners

Ever wondered how those captivating online games you can’t get enough of are created? Well, I’m here to shed some light on that. The secret magic behind many of these addictive virtual experiences is HTML – an accessible and versatile language used in web development. With a touch of creativity and the right guidance, you too can harness the power of HTML to create your very own game!

Now, I know what you’re thinking: “Coding? Isn’t that incredibly complex?” It’s true that coding might seem daunting at first glance. But trust me when I say it’s not as intimidating as it seems! In fact, creating a game with HTML is an excellent project for beginners looking to dip their toes into the world of programming.

So let’s get started, shall we? By the end of this guide, you’ll have all the tools and knowledge needed to breathe life into your imaginative game ideas using nothing but  HTML !

Understanding the Basics of HTML

Diving right into it, HTML, or HyperText Markup Language, is what forms the backbone of every webpage we interact with. It’s the standard language for creating those webpages and web applications. A markup language? I hear you ask. Indeed! It means you’re using tags to define elements within your document.

Let’s take a moment to look at an example:

This might seem like a bunch of gibberish now, but don’t worry – I’ll break it down for you.

First things first:  <!DOCTYPE html>  This little line here is essentially telling your browser “Hey, expect some HTML5 in this document.” Now that’s out of the way, we can move onto the real meat and potatoes.

The  <html>  tag does exactly what it says on the tin – it encapsulates all your other tags which make up your webpage. Inside this tag, there are two important sections:  <head>  and  <body> .

In our sample above,  <head>  contains only one child element:  <title> . The text placed between these opening and closing title tags will appear as the name of your tab in most browsers. In this case? “My First Webpage”.

Moving along – let’s delve into that juicy  <body> . Here is where all our content goes; everything we want visible on our page must be contained within these body tags.

You’ll see there’s an  <h1>  tag (the largest heading size) with ‘Welcome to my website!’, followed by a simple paragraph wrapped in a tidy little pair of  p  tags saying ‘I’m excited to learn HTML.’ And that’s it! You’ve got yourself a website.

HTML tags are vast, and they all come with different functionality. For example, you can use the  <img>  tag to add images to your page:

The  src  attribute is where you’ll put the path or URL to your image file. The  alt  attribute is an alternative text description of the image – this is important for accessibility reasons (for visually impaired users using screen readers), as well as if your image fails to load.

HTML isn’t just about making things appear on a webpage – it’s also about structuring those elements in a way that makes sense semantically. But hey, we’re just scratching the surface here, there’s so much more to uncover!

Exploring Game Design Concepts

I’ll be the first to admit, diving into game design can feel a bit like trying to navigate through a maze. But don’t worry, I’m here to guide you through it! The first thing we need to do is understand what makes a game tick. At its core, every game revolves around three main elements:

  • Mechanics: This refers to the rules and procedures that drive the gameplay forward.
  • Dynamics: These are the behaviors that emerge from the mechanics – how players interact with the game.
  • Aesthetics: This encompasses everything visual within your game – from character design to background scenery.

Let’s break this down further by creating a simple HTML-based dice-rolling game. We’ll use JavaScript for logic and CSS for aesthetics.

Take a look at this example of an HTML button element that will serve as our ‘roll dice’ button:

And here’s where we link it up with some JavaScript:

Our button (mechanic) triggers an event (dynamic), resulting in an alert box displaying our dice result (aesthetic). It’s really that simple! You could even add multiple dice or different types of dice into your mix – D6s, D10s, or even those crazy D20s!

One key aspect of HTML games is interactivity. In other words, how does your player interact with your game? Let’s demonstrate using another HTML tag – the  input  field:

This time we’re asking for a player input. We can then use JavaScript to compare the guess against a pre-set answer:

In this example, our  input  field and button are mechanics, deciding whether the player’s guess is correct or not is a dynamic, and the alert box serves as an aesthetic element.

Remember, these are just basic examples – there’s so much more you can do! Want your game to have multiple levels? Add in some additional HTML elements. Need to keep score? Just toss in some JavaScript variables. The possibilities are endless!

Creating Your First HTML Game: Step-by-Step Guide

So you’re ready to dive into the exciting world of game development? Good news! You’ve come to the right place. Let me guide you through the process of creating your first HTML game step by step.

To kick things off, we’ll need a basic understanding of three core technologies: HTML (HyperText Markup Language), CSS (Cascading Style Sheets), and JavaScript. These are the backbone of any web-based game. Don’t worry if you’re not familiar with these yet; I’m here to help!

HTML is like our game’s blueprint. It sets up the structure and content, such as text or images. Here’s an example:

This code creates a webpage with a heading and a paragraph. But how can we make it interactive? That’s where JavaScript comes in, adding functionality to our static HTML.

Next on our list is CSS, which styles our game – giving it colors, fonts, and layouts. Using CSS effectively can turn a dull-looking game into something visually stunning!

This snippet changes the background color of the page to light blue and centers white-colored header text.

Now that we have outlined these three crucial components let’s get started on building a simple game – ‘Guess The Number’. We’ll use JavaScript for logic, HTML for structure, and CSS for styling.

The idea behind ‘Guess The Number’ is straightforward – the computer generates a random number between 1 and 100, and players must guess what it is.

Here’s some basic code you could use:

This JavaScript code generates a random integer between 1 and 100, then prompts the player to guess the number. If their guess is correct, they’re congratulated; if not, they’re told the correct answer.

I hope this guide gives you a clear starting point for your journey into HTML game development. Remember that practice makes perfect – so start coding!

Troubleshooting Common Issues in HTML Game Development

Let’s face it, coding an HTML game can be a fun but challenging endeavor. Between unexpected bugs and puzzling syntax errors, you’re bound to run into a few hiccups along the journey. But don’t worry, I’m here to guide you through some common issues in HTML game development and how to troubleshoot them.

One of the most frequent problems that developers encounter is dealing with inconsistent browser behavior. It’s not unusual for your game to work perfectly on one browser and then completely fail on another. This issue often arises due to differences in how browsers interpret HTML and JavaScript code. To mitigate this problem, always test your game on multiple browsers during development.

Another common roadblock is handling user input effectively. For example, if players are using keyboard events as controls, you might experience issues like ‘keydown’ events firing repeatedly when a key is held down.

To prevent this from happening, use the ‘keyup’ event instead:

Performance optimization can also pose significant challenges in HTML game development. If your game experiences lag or delays – chances are high it’s related to inefficient JavaScript or heavy DOM manipulation causing re-flows and repaints. In such cases:

  • Make sure your JavaScript loops aren’t running unnecessarily.
  • Utilize canvas for games requiring intense graphics.
  • Use requestAnimationFrame() instead of setInterval() for smoother animations.

HTML game development isn’t without its fair share of obstacles. Still, with a bit of patience and perseverance, you can effectively troubleshoot these common issues. Now go forth and code – your gaming world awaits!

html tutorial game

Cristian G. Guasch

Related articles.

  • How to Make a Vertical Line in HTML: A Simple Guide for Beginners
  • How to Disable a Button in HTML: Your Quick and Easy Guide
  • How to Make Checkboxes in HTML: My Simple Step-by-Step Guide
  • How to Make a Popup in HTML: A Simple, Step-by-Step Guide for Beginners
  • How to Float an Image in HTML: Simplifying Web Design for Beginners
  • How to Use iFrame in HTML: A Comprehensive Beginner’s Guide
  • How to Add Audio in HTML: A Comprehensive Guide for Beginners
  • How to Print in HTML: Your Essential Guide for Webpage Printing
  • How to Draw Lines in HTML: A Swift and Simple Guide for Beginners
  • How to Add Canonical Tag in HTML: Your Easy Step-by-Step Guide
  • How to Make Slideshow in HTML: Your Quick and Easy Guide
  • How to Use Span in HTML: Unleashing Your Web Design Potential
  • How to Embed Google Map in HTML: A Quick and Easy Guide for Beginners
  • How to Add SEO Keywords in HTML: My Simplified Step-by-Step Guide
  • How to Add a GIF in HTML: A Simple Guide for Beginners
  • How to Change Fonts in HTML: Your Ultimate Guide to Web Typography
  • How to Make an Ordered List in HTML: A Straightforward Guide for Beginners
  • How to Add Bullet Points in HTML: Your Quick and Easy Guide
  • How to Move Text in HTML: My Expert Guide for Web Developers
  • How to Unbold Text in HTML: A Straightforward Guide for Beginners
  • How to Create Pages in HTML: A Step-by-Step Guide for Beginners
  • How to Use PHP in HTML: An Expert’s Guide for Seamless Integration
  • How to Make Multiple Pages in HTML: A Comprehensive Guide for Beginners
  • How to Embed a Website in HTML: Your Simple Guide to Seamless Integration
  • How to Create a Box in HTML: A Simple Guide for Beginners
  • How to Make a Search Bar in HTML: Simplified Steps for Beginners
  • How to Add Padding in HTML: A Simple Guide for Web Design Beginners
  • How to Send HTML Email in Outlook: Your Step-by-Step Guide
  • How to Make a Form in HTML: Your Easy Guide for Better Web Design
  • How to Put Text Next to an Image in HTML: A Simple Guide for Beginners
  • How to Use Div in HTML: Your Ultimate Guide on Mastering Division Tags
  • How to Wrap Text in HTML: Mastering the Art of Web Design
  • How to Redirect to Another Page in HTML: A Simple, Effective Guide for Beginners
  • How to Center a Div in HTML: My Expert Guide for Perfect Alignment
  • How to Add a Target Attribute in HTML: A Simple Guide for Beginners
  • How to Link Email in HTML: My Simple Guide for Beginners
  • How to Use JavaScript in HTML: A Comprehensive Guide for Beginners
  • How to Make List in HTML: A Comprehensive Guide for Beginners
  • How to Make a Button in HTML: A Simple Guide for Beginners
  • How to Add a Line Break in HTML: Your Quick and Easy Guide
  • How to Embed a Video in HTML: A Simplified Guide for Beginners
  • How to Add a Favicon in HTML: Your Easy Step-by-Step Guide
  • How to Change Font Size in HTML: A Simple Guide for Beginners
  • How to Center a Table in HTML: Streamlining Your Web Design Skills
  • How to Add Space in HTML: Your Guide for a Cleaner Code Layout
  • How to Change Image Size in HTML: Your Quick and Easy Guide
  • How to Indent in HTML: A Simple Guide for Beginners
  • How to Add a Link in HTML: Your Easy Step-by-Step Guide
  • How to Make a Table in HTML: Your Ultimate Guide to Mastery
  • How to Add an Image in HTML: A Step-by-Step Tutorial for Beginners

Game Development Tutorials by Spicy Yoghurt

Spicy Yoghurt | Last updated: 9 March 2019 | HTML5 game tutorial

Develop an HTML5 game

Create your own game with HTML5 and JavaScript. Learn about game loops, animations & sprites, collision detection, physics and user input. Follow this tutorial series and end up with a basic HTML5 game of your own.

What is an HTML5 game?

HTML5 logo

This tutorial series is all about building an HTML5 game. But what exactly does that mean? Well, when people talk about HTLM5 games they mostly use it as a buzzword, because you can't really create a decent game by using just HTML5. Here's why:

  • HTML5 is a markup language (HTML stands for HyperText Markup Language, version 5 is the latest installment)
  • It only describes the structure and content of a web page and links it to a style sheet
  • It's not an actual programming language

This means that HTML5 isn't suited to write the logic that is needed to create a game. Then what is an HTML5 game? It's the name of a game build by using a collection of new web techniques, which include HTML5 , but also CSS3 and JavaScript .

Actually, most of the time you'll be dealing with JavaScript . JavaScript is an actual programming language and you can write game logic with it. You'll use HTML5 to create your drawing board and JavaScript to draw your game on it.

To say it in short, whenever people talk about an HTML5 game, they actually mean an HTML5, CSS3, JavaScript game.

What to expect from this tutorial series?

In this tutorial series you'll build a simple HTML5 game that will let you control a player with user input. The series will take you through the following steps:

  • Set-up an HTML5 file with a canvas
  • Learn how to draw shapes and text
  • Create a game loop
  • Animate objects and use easings
  • Detect collisions and apply physics
  • Draw images and sprite animations
  • Control game objects with user input

Here's a quick preview of what you are going to make along the way:

Learn how to create your own game

The aim of this tutorial series is to let you get familiar with game programming in HTML5, and game programming in general. If you haven't done this before, it requires a new way of thinking. You don't just run a piece of code once, but you'll do this many times per second inside a game loop and this takes a whole new approach.

Don't expect the next Call of Duty game. This is just a basic series of tutorials to get you started. You'll start with nothing and build your game from the ground up.

You will learn how to implement common game programming techniques and how to avoid common mistakes. You will get a basic understanding of game development principles.

What happened to Adobe Flash?

Adobe Flash logo

It's time for a brief history lesson, to better understand the role HTML5 plays in the world of browser games. Because, HTML5 wasn't always around. Before the release of HTML5, people used to create browser games with Adobe Flash .

Flash was great for making things like animations and games , and there wasn't really any other option to create content like this for the web at the time. Also, as a developer, you didn't have to take different web browsers into account while developing, the Flash Player took care of that.

However, a big downside of Flash was the lack of mobile support . Apple had a lot to do with this because it didn't want to support the Flash Player on its mobile devices, claiming Flash had bad performance and security issues . Regardless of whether the claims were completely fair and true, it did become the start of Flash getting a bad image and losing popularity.

Years later, the major browsers are ending Flash Player support more and more too. At the end of 2020 Adobe will stop updating and distributing the Flash Player . This will be the definitive end of the era of Flash games. So it's time for HTML5 to take this spot.

The rise of HTML5

Starting from its release in 2012, HTML5 was hyped-up to be the new holy grail for browser games. It was supposed to completely make Flash obsolete.

This was easier said than done because it wasn't really that easy to create a decent game with HTML5 at the time. All of a sudden, as a developer, you had to take different browsers and devices into account. And it took quite some time before all HTML5 functions were streamlined and standardized on all browsers. Seemingly simple things, like playing sounds for example, were a big problem. Things that Flash used to make easy to implement.

Luckily this has improved much over the years. Right now HTML5 has great browser support and a wide selection of tools to support development. It's ready to take the place of Flash as king of the browser games.

Even Adobe Flash had an update to create HTML5 animations and games and was renamed to Adobe Animate to get rid of the notorious reputation of Flash.

Benefits of HTML5

One of the biggest advantages that HTML5 holds over Flash is the possibility to run content on mobile devices . This doesn't mean that with HTML5 every game will automatically run on every device. Especially things like sounds and scaling might need some attention, but you can make it work. And when you do, you can show off your game to everyone who owns a mobile phone. So that's about... everyone.

Run your HTML5 game on all devices

Let's get started with your own game!

That's enough background information for now. You now know a little bit more about HTML5 and how this tutorial series is set-up. It's time to start building your own HTML5 game!

Click next to take the first step in this series and start with setting up an HTML5 page with a canvas. You'll be performing your first drawing operation soon.

In this tutorial series

More tutorials

Leave a comment

The Complete Guide to Building HTML5 Games with Canvas and SVG

David Rousset

I’m currently spending most of my time explaining to students, hobbyists, professional developers and teachers how to build games using HTML5. Then, I recently thought, rather than keeping all these details for small audiences, wouldn’t it be smarter to share it with you? This article is then based on my own experience. I will probably omit some crucial things some of you may know. But I’ll try to update this post with my own new discoveries and, of course, based on the feedback you kindly provide in the comments or via Twitter .

But why are so many people currently interested in HTML5 Gaming?

Canvas and svg: two ways to draw on the screen.

Canvas vs SVG

Useful libraries and tools

html tutorial game

Physics Engine

html tutorial game

Handling the multi touch events

html tutorial game

Building connected games

html tutorial game

Some beginners’ tutorials

html tutorial game

Frequently Asked Questions about HTML5 Games with Canvas and SVG

What are the basic tools needed to start building html5 games with canvas and svg.

To start building HTML5 games with Canvas and SVG, you need a text editor, a modern web browser for testing, and a basic understanding of HTML, CSS, and JavaScript. Text editors like Sublime Text, Atom, or Visual Studio Code are great for writing your code. Modern browsers like Chrome, Firefox, or Safari have built-in developer tools that can help you debug your code. Lastly, knowledge of HTML, CSS, and JavaScript is crucial as these are the building blocks of your game.

How can I animate objects in HTML5 games?

Animation in HTML5 games is achieved through the use of the Canvas API’s requestAnimationFrame method. This method tells the browser to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. This results in smoother animations compared to using setInterval or setTimeout.

How can I handle user input in HTML5 games?

User input in HTML5 games is typically handled through event listeners. You can listen for keyboard events like ‘keydown’ or ‘keyup’ to move a character, or mouse events like ‘click’ or ‘mousemove’ to shoot a bullet or drag an object. The event object passed to your event handler function contains useful information like the key code or mouse position.

How can I add sound effects to my HTML5 game?

Sound effects can be added to HTML5 games using the Audio API. You can create a new Audio object, set its src attribute to the URL of your sound file, and call the play method to play the sound. You can also control the volume, loop the sound, and listen for events like ‘ended’ or ‘canplay’.

How can I create a game loop in HTML5?

A game loop in HTML5 can be created using the requestAnimationFrame method. This method calls a function you provide to update your game state and redraw the game screen before the next repaint. The game loop is the heartbeat of your game, ensuring that the game state is updated and the screen is redrawn at a smooth and consistent rate.

How can I detect collisions in my HTML5 game?

Collision detection in HTML5 games can be done in several ways, depending on the complexity of your game. For simple games, you can use bounding box collision detection, where you check if the bounding boxes of two objects overlap. For more complex games, you might need to use pixel-perfect collision detection or a physics engine.

How can I optimize my HTML5 game for better performance?

There are several ways to optimize your HTML5 game for better performance. You can use requestAnimationFrame for smoother animations, use offscreen canvases to reduce redraws, use web workers to run heavy computations in the background, and use the performance API to measure and improve your game’s performance.

How can I make my HTML5 game responsive and mobile-friendly?

Making your HTML5 game responsive and mobile-friendly involves designing your game to adapt to different screen sizes and input methods. You can use CSS media queries to adjust your game layout for different screen sizes, and handle touch events in addition to mouse and keyboard events for mobile devices.

How can I save and load game state in HTML5 games?

Saving and loading game state in HTML5 games can be done using the Web Storage API. This API provides two objects, localStorage and sessionStorage, which you can use to store key-value pairs. You can save your game state as a JSON string and load it back when the game starts.

How can I debug my HTML5 game?

Debugging your HTML5 game can be done using the developer tools built into your web browser. These tools allow you to inspect your HTML, CSS, and JavaScript code, set breakpoints, step through your code, watch variables, and see any errors or warnings. You can also use console.log statements to log information to the console.

Build A JavaScript Game Step-By-Step (Using HTML, CSS + JavaScript)

Jacinto Wong

Jacinto Wong

hero image

In This Tutorial:

Step 1: building the user interface (ui) with html, step 2: refining the user interface (ui) with css, step 3: javascript - player selection, step 4: javascript - computer selection, step 5: javascript - check results, step 6: javascript - reset all, step 7: javascript - confetti functionality, step 8: javascript - module refactoring, did you get it built.

Want to improve your JavaScript skills , while also showing your appreciation for the Big Bang Theory?

Well, good news! In this tutorial, I’ll walk you through how to code and create a more complex version of the classic rock-paper-scissors game i.e. rock, paper, scissors, lizard, spock!

rock paper scissors lizard spock game

I've got your back with the CSS, including the media queries for seamless responsive design on smartphones. This way, we can dive right into the game's functionality.

rock paper scissors lizard spock game finished in javascript

Our game will feature dynamic elements, such as:

  • Executing turns with a single click on an icon
  • Automatic computer moves with random selections
  • Score tracking for player and computer
  • A results message at the bottom
  • Confetti falling when the player wins a round, and
  • Game reset and restart by clicking on an icon

Moreover, we'll explore JavaScript modules and import confetti functions from a separate file.

You can find the code to work on this project here:

  • Final Version Demo

Quick side note before we dive in

If you stumbled upon this page simply due to your love of the Big Bang Theory and want to learn to code (or more likely you're having some trouble learning to code), then I highly recommend you check out Andrei’s Coding Bootcamp course .

I personally learned to code from Andrei many years ago using his Coding Bootcamp (Complete Web Developer). Thanks to that, I've been a Developer for 5+ years now and even become an instructor myself as well.

It all started from taking Andrei's Coding Bootcamp and I'm just one of 1,000s of students that have a similar story to mine .

So if you want to learn to code and actually make a career out of it, there is still no better place in my mind!

learn web development

Andrei didn't even ask me to say any of this but I am anyways because I have been in your shoes as a complete beginner.

It makes sense that it's one of the most popular and highly-rated coding bootcamps online. He is constantly updating it (more than any other coding bootcamp I've seen), he goes way above and beyond, and actually makes learning fun.

And web development is a great career and not just because the money is good.

... but the money is good: The average salary for a Full-Stack Web Developer at the moment is around $117,800 in the US .

full-stack web dev salary 2024

Not bad eh!?

Alternatively, if you’re already an aspiring Developer or Junior Developer looking to improve your skills by building some JavaScript projects (that you can also add to your portfolio), then I'd love to help you out.

The project we're going to walk through in this tutorial is just 1 of the 20 projects you'll get to build in my JavaScript portfolio projects course .

If you find yourself getting stuck somewhere in this tutorial, then it might be helpful for you to see me building the project step-by-step alongside you (plus you'll be able to ask me questions directly on Discord).

advanced javascript portfolio projects

Oh, and FYI: If you join Zero To Mastery, you get access to all of the courses on ZTM , not just the two I've mentioned.

Alright, with that out of the way, let’s get building this JavaScript game project shall we?

First things first, there is a template for this project that will make it easier to follow along.

You can get it here .

Open it in Visual Studio Code (VSC) and launch it with a live server.

Creating the HTML structure

Now that you have the project template, let's start building our HTML:

Next, we need to grab the icons for the game images. I recommend you use FontAwesome icons .

get icons

They have all the necessary icons to create this game, as seen below:

RECOMMENDED ICONS

We'll then use these icons as buttons to select as our choice in each match.

Create the player container

Start by adding your icons in the player container. (If you use other icons, be sure to reflect that here).

Create the computer container

Next, we need to make a computer container for us to play against, so go ahead and duplicate the player container for the computer container, as the code is almost identical.

You just need to replace all instances of 'player' with 'computer', but you can do that with the multi-select tool:

Reset icon and results container

Lastly, add a reset icon and a container to display the results:

Save your file and check the progress. It should end up looking like this:

initial build

Not bad right? It needs some improvements, but we can refine these in our CSS.

I've included most of the CSS for this tutorial in the project template, but let’s go over a few key aspects of how we can improve, what we’re going to refine, and why.

Improve the body background for better visibility

Let's start with the body background. We want it to be slightly gray so that it stands out on white screen. Right now it kinds of blends:

BLEND

So go ahead and add a color to help it pop, like so:

In theory, you could use any color you want.

Edit the game container UI

Next, let's style the game container itself, and give it some shading, so it pops even more, like so:

pop

Not bad right? We can edit it with the following code:

The background looks good, but the layout is a little bit of a mess.

With that in mind, let’s fix the header div and the icons' layout. Additionally, we'll check the mobile responsiveness of our container.

Edit the Header styling

Let’s start by adjusting the height and border radius of the header, as it’s currently not rounded, like the bottom of the body.

Save and check, and it looks much better.

add a rounded header

Check mobile responsiveness

Now, let's examine the smartphone vertical view.

CHECK THE INTIAL MOBILE VIEW

It’s running right up to the edge of the screen. Ideally, we want the margins on the left and right to display the shadow.

To fix this, at the bottom of our CSS, I've added several media queries, to update the game container width:

Save and check.

mobile view with margins

Fantastic. Now it looks great on both large smartphones and iPhones.

Edit the icon's color and highlight the selection

Ok, let’s do 3 things to improve the icons:

  • Change the icon's initial color
  • Add an indicator to help identify which option is being selected
  • Also, let's add different colors for the player and computer

We can do this like so...

Adding player and computer icon colors to help differentiate

added icon colours

The splash of color looks fantastic!

Test adding a selection identifier

Next, we'll add a selected class, for when one of our icons is clicked. Let's test it by adding the class manually to our paper element in the HTML:

Use !important to override the color property in this case:

Save and check to see if it works!

ICON turns black

Now that you know it works, go ahead and remove the !important override. We’ll add the functionality in just a second, but we have some final tweaks to do first.

Edit the icon layout

Currently, there’s a large margin on the right-hand side of the icons, so let’s remove the margin on the last icon in each row:

working as intended

We're done with our styling so now it's time to move on to functionality!

We know that the highlighted icon should turn black, however, we haven’t added the functionality for that to work just yet, so let’s do it now.

First, create the constants for the HTML elements that we want to reference:

Next, create the selection logic for the player icons by adding an onclick attribute to the HTML:

Now, create the select function in JavaScript:

When we save and check the console, we can see the value is being passed through.

select function

When we click on an icon, it’s being selected.

Now, let's use this to figure out our selection logic for our CSS, as we want the clicked icon to turn black and update the choice text as well.

Remove the console log and use a switch statement :

ICON turns black

It works, but still needs a little work.

Why? Well, updating the text selection choice works fine, but once we select an icon, it stays selected permanently, which is not great.

selection stays locked

We want it to change between each new selection, as well as keep updating the text (which currently works).

Adding a resetSelected function

We can solve this by adding another function to reset the icons after each selection. We'll use the allGameIcons array for this.

Start by creating the resetSelected function:

Then, call resetSelected from the select function, before assigning the selected class:

Save and check to see if it works.

working as intended

The player selection is fully functional now, so in the next step, we'll focus on the computer-related functionality.

In this section, we'll create logic for the computer to make a random selection and display the selection like how we're displaying the player selection.

First, create a new function named checkResult which will call other functions:

Then, create a variable at the top for containing a string of the computerChoice :

Now, use a Math method called random to get a random number. We will divide this into 5 ranges and select based on that:

random numbers working

Now, use a series of if statements to change the computerChoice value, like so:

random computer choice

Next, reuse the same functionality from the player select function and create a new function called displayComputerChoice :

However, this won’t work on its own.

We also need to call the displayComputerChoice function in the checkResult function:

Save and check, and it should look like this:

WE WON

The computer selection is now working! In the next step, we will implement the logic of the game.

So far, we’ve created a working project that follows the rules for a standard game of rock, paper, scissors. However, the rules are different in rock, paper, scissors, lizard, spock, so we need to adjust this in the code.

As a quick recap:

  • Scissors cut Paper
  • Paper covers Rock
  • Rock crushes Scissors

But now we also have:

  • Rock crushes Lizard
  • Scissors decapitates Lizard
  • Lizard eats Paper
  • Lizard poisons Spock
  • Paper disproves Spock
  • Spock smashes Scissors
  • Spock vaporizes Rock

Fortunately, it’s not too complex to code these additional rules, and in this section, we'll create the logic of the game itself.

So let’s work through this.

We have an object with each possible choice, containing its own object that has an array of the two choices it defeats:

Create global variables for the score:

Then update the select and checkResult functions to pass the playerChoice as a parameter:

Then go ahead and create the updateScore function:

Add in the ability to check for a tie:

And then check to see if it works…

tie function works

Now to the real logic. We’ll create an else statement if we are not tied.

Within that statement, we will create a choice constant, which will call an item from the choices array, matching the playerChoice to a key name:

First, we will modify our console log and see how it works.

array works

As you can see in the example, we chose rock. The array then clarifies that rock can beat both scissors and lizard. Because the computer chose scissors, we won!

Go ahead and play a few rounds to check that it all works, and keep an eye on the code as you do this.

Notice that when the player wins the value is 0 or 1, which means that the computer choice was found in the defeats array as the first or second item.

If it is not in the array, it returns -1.

winning value

So, now, we know that if the number is greater than -1, then the player has won .

Let’s add in the logic to display this.

We already know that when the value is 0 or 1 , then the player wins, the score goes up and the message says “ You won ”.

However, when the computer wins nothing happens, so let’s fix that, and make it say “ You lost ” when the player loses.

We just need to add an else statement and mirror what we were doing for updating our text and the score.

The game logic is now complete! In the next step, we will add the ability to reset everything and start over.

In this section, we'll create a function to reset everything and start over. This will include resetting the score, player and computer choices, and selected icons.

First, let's clean up the HTML by removing any unnecessary text that was initially hardcoded, since our JavaScript is now populating the content.

Create the resetAll function

This function will:

  • Reset the player and computer scores
  • Update the score elements in the user interface
  • Clear the player and computer choice text
  • Clear the result text, and
  • Reset the selected icons by calling the resetSelected function

It looks like this:

In the HTML file, add the onclick attribute for the resetAll function to the "Reset" button:

Since we want the initial score values to be displayed when the page loads, call the resetAll function on startup:

Save your changes and check the result in your browser.

The reset functionality should now be working as expected. When you click the "Reset" button, the scores, choices, and selected icons will reset to their initial state.

By following these steps, you've added a reset function to the game. In the next step, we'll work on making winning a round a little more exciting.

In this section, we'll add confetti functionality to the game.

Basically, when the player wins a round, the confetti show. Then, it will stop immediately if the next round is a tie or if the player loses.

We'll use an external script for the confetti effect, so go to the following link and download the confetti.js file .

Unzip the downloaded file, then copy and paste the confetti.js file into your project folder. Then, go ahead and open the file in your code editor (e.g., Visual Studio Code).

Copy the entire content of confetti.js and paste it at the bottom of your main JavaScript file.

We will need to modify it slightly, as we want to be able to call the functions, so we will remove the function wrapping everything , IIFE (immediately-invoked function expression)

To test the confetti effect, call the startConfetti function when the page loads:

The confetti effect should look something like this:

confetti

Adjust the confetti settings according to your preference.

For example

You can change the maxCount to 100 and the animationSpeed to 10.

Now, we need to call the startConfetti , stopConfetti , and removeConfetti functions at the appropriate places in our code.

First, remove the startConfetti function call at the bottom of the script.

Then, call the startConfetti function when the player wins a round, by adding it inside the if statement that checks if the player has won:

Call the stopConfetti and removeConfetti functions inside the resetSelected function to stop the confetti effect every time the user selects an icon:

Save your changes and test the result in your browser. The confetti effect should start when the player wins and stop instantly when the next round begins.

You've now added confetti functionality to the game. In the next step, you can refactor the code and learn how to implement modules in JavaScript for better organization and separation of concerns.

Recommended reading references:

  • Understanding ES6 Modules
  • A history of different JavaScript module formats
  • JavaScript modules by Mozilla

In this step, we'll refactor our project to use ES Modules for better organization and separation of concerns. This will involve making changes to the script.js, confetti.js, and index.html files.

First, cut the confetti-related code from your script.js file and paste it into the confetti.js file.

Then, at the bottom of the confetti.js file, add the following line to export the confetti functions:

In the script.js file, import the confetti functions at the top:

In the index.html file, add the type attribute of module to the script.js:

Alright so let’s see if this works.

Test the confetti functionality by calling the startConfetti function at the bottom of the script.js file:

Save your changes and check the result in your browser. The confetti effect should still start as expected.

Once you can see that it works, let’s tweak this.

Go ahead and remove the startConfetti function call from the bottom of the script.js file. Then save your changes and try selecting an icon in your browser.

The confetti effect may not work as expected due to the module's scope. To fix this, you can pass the functions from the script.js file to the global window object .

Below your two functions ( resetAll and select ), add the following lines:

Save your changes and test the result in your browser, and everything should work as expected.

Congratulations! You have successfully refactored your project to use ES Modules. This enhances the organization and separation of concerns in your code.

So there you have it. Hopefully, you’ve been following along and building as you read through - if not, then get it built now and improve that portfolio to prep for that dev interview!

Although this is a fairly fun project, we’ve actually covered a lot of different topics here.

  • We've built from scratch using HTML, CSS, and JavaScript
  • We've covered various aspects of web development, including structuring HTML elements, styling with CSS, handling user interactions, and implementing game logic with JavaScript
  • We added confetti animation for a more engaging user experience
  • And we refactored the project to use ES Modules for better organization and separation of concerns!

No joke - By completing this tutorial, you've gained valuable skills in web development and deepened your understanding of how HTML, CSS, and JavaScript work together to create dynamic and interactive web applications. You can now take these skills and apply them to your own projects or continue learning and exploring more advanced topics in web development.

If you want more projects like this, be sure to check out my 20 Advanced JavaScript Projects course.

Or, if you struggled with building this game, and want a deep dive back into JavaScript, go ahead and check out ZTM’s Complete Web Developer course .

You can watch the first few videos here for free!

The Complete Web Developer in 2024: Zero to Mastery

The Complete Web Developer in 2024: Zero to Mastery

Learn to code from scratch and get hired as a Web Developer in 2024. This full-stack coding bootcamp will teach you HTML, CSS, JavaScript, React, Node.js, Machine Learning & more.

JavaScript: The Advanced Concepts

JavaScript: The Advanced Concepts

Learn modern, advanced JavaScript practices to become a top 10% JavaScript Developer. Fun fact: this course is even used as a reference for some FAANG company interview processes.

JavaScript Web Projects: 20 Projects to Build Your Portfolio

JavaScript Web Projects: 20 Projects to Build Your Portfolio

Get hired or your first client by building your dream portfolio of modern, real-world JavaScript projects. Never spend time on confusing, out of date, incomplete tutorials anymore!

More from Zero To Mastery

[Guide] Computer Science For Beginners preview

You DO NOT need a CS Degree to get hired as a Developer. Learn Computer Sciences Basics today with this free guide by a Senior Dev with 10+ years of experience.

Yihua Zhang

Hey Web Dev - do you want to sharpen your JavaScript skills? Then come join me and let's start building some awesome beginner friendly JavaScript projects to boost your portfolio & skills.

Jacinto Wong

Want to add some life to your web projects? In this tutorial, you'll learn how to code animations using CSS and JavaScript (including anime.js & three.js).

< BACK TO COMPONENTS

Creating a Tetris Game with HTML, CSS and JavaScript

Faraz

By Faraz - April 15, 2023

Learn how to create a Tetris game from scratch using JavaScript with this beginner-friendly guide. Build the game mechanics, levels, and scoring system step-by-step.

creating a tetris game with html css and javascript.jpg

Table of Contents

  • Project Introduction
  • JavaScript Code

Tetris is a classic puzzle game that has been entertaining players since its inception in the 1980s. The game involves manipulating falling shapes, or tetrominoes, to form complete lines and clear them from the game board. It is a simple yet challenging game that has stood the test of time and has been adapted to various platforms over the years.

In recent years, game development has become more accessible to a wider audience, thanks to the popularity of web and mobile app development. With the rise of JavaScript as a leading programming language for web development, it is now possible to create a Tetris game using JavaScript and web technologies.

In this article, we will guide you through the process of creating a Tetris game using JavaScript. We will start by setting up the game environment with HTML and CSS, then move on to implementing game mechanics with JavaScript. We will cover essential game features such as block rotation, movement, and collision detection, as well as creating multiple game levels and a scoring system.

In addition, we will explore ways to enhance the game experience with visual effects and provide a complete guide to deploying the Tetris game on the web. Whether you are a beginner or an experienced developer, this article will provide you with the essential knowledge and skills to create a fun and engaging Tetris game with JavaScript.

Let's start making an amazing Tetris game using HTML, CSS, and JavaScript step by step.

Join My Telegram Channel to Download the Projects Source Code: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Code by: Shahn-Auronas

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our Tetris game.

After creating the files just paste the following below codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Below is a basic HTML code that includes a Tetris game using JavaScript.

The <!DOCTYPE html> is a declaration that specifies the document type and version of HTML used in the document.

The <html> element is the root element of the document, containing all other elements.

The <head> element contains metadata for the document, such as the document title and external resources. In this case, it includes a title of "TETRIS GAMES WITH JAVASCRIPT" and a link to an external stylesheet named "styles.css".

The <body> element contains the content that is displayed in the web browser.

Inside the <body> element, there is a <div> element with the id of "tetris". This div contains two child elements, another <div> element with the id of "info" and another <div> element with the id of "canvas".

The <div id="info"> element contains several child elements, including a <div> element with the id of "next_shape" that is empty and will display the next shape to appear in the game, four <p> elements with the id of "level", "lines", "score", and "time" that will display the game's statistics, a <button> element with the id of "start" that will start the game, and a <p> element with the class of "red" that will display instructions to pause the game by pressing the Esc button.

The <div id="canvas"> element is where the Tetris game board will be displayed.

Finally, there is a <script> element that includes a JavaScript file named "script.js" that contains the code for the Tetris game.

This is the basic structure of our Tetris game using HTML, and now we can move on to styling it using CSS.

Press the Esc button to pause

html tutorial game

Step 2 (CSS Code):

Once the basic HTML structure of the Tetris game is in place, the next step is to add styling to the Tetris game using CSS. CSS allows us to control the visual appearance of the website, including things like layout, color, and typography.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to style our Tetris game.

Below is a CSS stylesheet that defines the styles for the HTML elements used in the Tetris game.

The body selector applies styles to the entire body of the document, setting the overflow to hidden and the background color to a light gray.

The #tetris selector applies styles to the div element with the id of "tetris", setting the width to 360 pixels, adding a 1-pixel black border, and adding 20 pixels of padding.

The #canvas selector applies styles to the div element with the id of "canvas", setting the width to 200 pixels, the height to 440 pixels, and the background color to black. It also positions the element relative to its parent, sets the font color to white, and includes an h1 selector that sets the font size to 30 pixels and centers the text.

The .piece selector applies styles to all elements with the class of "piece", setting a 1-pixel white border and positioning them absolutely.

The #start selector applies styles to the button element with the id of "start", setting an animation that causes the button to blink, adding a light green background color, a 2-pixel border radius, and setting the font color to dark gray.

The @keyframes rule defines an animation for the #start selector that causes the button's outline to blink.

The .red selector applies styles to all elements with the class of "red", setting the font color to red.

The .square selector applies styles to all elements with the class of "square", setting their position to absolute and their width and height to 19 pixels, with a 1-pixel white border.

The .type0, .type1, .type2, .type3, .type4, .type5, and . type6 selectors apply styles to the elements with the corresponding classes, setting their background color to different shades.

The #next_shape selector applies styles to the div element with the id of "next_shape", setting its position to relative, its background color to black, and its border to 1 pixel white. It also sets the width and height to 110 pixels.

The #info selector applies styles to the div element with the id of "info", setting its background color to black, its font color to white, and its width and height to 420 pixels. It also floats the element to the right and adds 10 pixels of padding.

This will give our Tetris game an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript to work our Tetris game.

The game is implemented as an object-oriented program that consists of several methods and properties. The game includes a game board, a canvas, and a set of Tetris shapes that are randomly selected and dropped onto the board.

The init method initializes the game by calling other methods to initialize the board, info, shapes, and key events. Then, it starts the game by calling the play method.

The initBoard method initializes the game board by setting the board height and width, creating an array to represent the board, and filling the array with zeros. The size of each square on the board is also set in this method.

The initInfo method initializes the game info by setting up the display for the next shape, level, time, score, and lines. It also calls the setInfo method to initialize the values for these info items.

The initShapes method initializes the game shapes by resetting the current squares, indicating that the current shape is not complete, shifting the temporary shapes array, selecting the next shape from the temporary shapes array, setting the current shape to the selected shape, initializing the next shape, setting the coordinates for the current shape to the spawn point, and drawing the current shape on the board.

The initNextShape method initializes the next shape by selecting the next shape from the temporary shapes array and drawing the shape on the canvas.

The initTempShapes method initializes the temporary shapes array by creating an array of all possible shape indices, and then shuffling the array using the Fisher Yates Shuffle.

The shiftTempShapes method shifts the temporary shapes array by removing the first element from the array.

The initTimer method initializes the timer by calling the incTime method every maxTime milliseconds using a setTimeout loop. This method also sets the speed of the game, the number of levels, and the initial values for the score, level, and time.

The play method starts the game by setting the active status to 1 and starting the timer.

The drawShape method draws a shape on the board by setting the color of each square in the shape to the color of the shape and drawing the square on the canvas.

The drawNextShape method draws the next shape on the canvas by setting the color of each square in the shape to the color of the shape and drawing the square on the canvas.

The bindKeyEvents method binds the key events to the game. When a key is pressed, the corresponding action is performed.

The move method moves the current shape in the specified direction. If the move is valid, the shape is redrawn on the board in the new position. If the move is not valid, the shape remains in its current position.

The rotate method rotates the current shape 90 degrees clockwise. If the rotation is valid, the shape is redrawn on the board in the new position. If the rotation is not valid, the shape remains in its current position.

The drop method drops the current shape down to the lowest possible position. The shape is redrawn on the board in the new position.

The clearLine method checks if a line is complete and removes the line if it is complete. The score is updated based on the number of lines cleared.

The incTime method increments the time by 1 and updates the time display.

The setInfo method initializes the info display by setting the value of the specified item to the specified value.

Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

Final Output:

html tutorial game

Conclusion:

In this article, we have provided a step-by-step guide to creating a Tetris game using JavaScript. We started by setting up the game environment with HTML and CSS, then moved on to implementing game mechanics with JavaScript. We covered essential game features such as block rotation, movement, and collision detection, as well as creating multiple game levels and a scoring system.

We also explored ways to enhance the game experience with visual effects and provided a complete guide to deploying the Tetris game on the web. By following this guide, you now have the essential knowledge and skills to create a fun and engaging Tetris game using JavaScript.

However, game development is an ongoing learning process, and there is always room for improvement and experimentation. We encourage you to continue exploring game development with JavaScript and to customize the game mechanics to suit your creative vision. With the right tools and resources, you can create a fun and unique game.

In conclusion, we hope that this article has provided you with the necessary knowledge and inspiration to create your own Tetris game using JavaScript. By following the steps outlined in this guide, you can create a game that is both challenging and enjoyable, and share it with others on the web.

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks! Faraz 😊

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox, related post.

  • Create a Secure Captcha Generator with HTML, CSS, and JavaScript
  • Creating Modern Tooltips with HTML and CSS: A Step-by-Step Tutorial
  • How to Create Glassmorphism Loading Animation with HTML and CSS Only
  • How to Sort HTML Table by Header Click | Sorting Data Tables
  • Building a Responsive Sports Dashboard using HTML, CSS, and JavaScript
  • Login Form with Captcha using HTML, CSS, and JavaScript (Source Code)
  • How I Created a Google Clone with HTML and CSS
  • Create a Birthday Countdown | HTML, CSS, JavaScript Tutorial

HTML5 Tutorials

This page showcases useful tutorials for HTML5 game developers. We’ve ensured that they easy to pick up, learn and internalize. Some of the highlights include:

Building a Chromecast Game : the Chromecast USB device is thought of as a device to beam content onto big screens. Its mainly used to beam movies and tv shows. What if we can build a fun casual game experience with this?

HTML5 Endless Runner: History and Design Thinking: instead of diving into code for endless runner games, we’d like to approach this from a high level form of thinking. At the very least, this tutorial will teach you how to approach building and designing an Endless Runner game in HTML5.

To view the full list, click here

License HTML5 Games

Are you a company looking to license HTML5 games? We recommend MarketJS.com , a B2B platform for licensing games.

MarketJS has over 300 HTML5 games for licensing. They also provide additional services such as game reskin , custom development , and white label portals .

Html5 Game Development

WHAT’S NEW

Unity’s pricing scheme changes, unity game engine pricing fee, open-source 3d game engine with sketchfab integration, modd.io updates – improved no coding required game engine, gpt3 voting board, new babylonjs feature within skybox, creating a mobile html5 rpg – guidelines for beginners, how to use html5 games to engage social media followers, running html5 games for online competitions, vertical platformer games using gdevelop.

In an open letter to the Unity community, the company announced the details of its pricing scheme changes. In the letter, the Personal plan will remain free and there will …Read more

Early in September 2023, Unity Technologies announced the Unity game engine pricing fee. Starting on 1 January 2024, the company will charge game developers a fee (2 tiers) for each …Read more

PlayCanvas, an open-source 3D game engine, has added Sketchfab integration into its latest updates. This improvement gives game developers access to Sketchfab’s high-quality 3D, AR, and VR content. To access …Read more

SEARCH OUR ARCHIVES

JavaScript Game Dev Tutorial – Build Gorillas with HTML Canvas + JavaScript

In this JavaScript game tutorial, you'll learn how to create a modern version of the 1991 classic game Gorillas using plain JavaScript and the HTML canvas element.

In this game, two gorillas throw explosive bananas at each other, and the first one to hit the other one wins the game.

We'll build out the whole game from scratch here. First, you'll learn how to draw on a canvas element with JavaScript. You'll see how to draw the background, the buildings, the gorillas, and the bomb. We won't use any images here – we'll draw everything using code.

Then we'll add some interactions and add event handlers. We'll also cover how to aim, how to animate the bomb across the sky, and how to detect if the bomb hit the other gorilla, or a building.

Throughout the tutorial, we'll be using plain JavaScript. To get the most out of this tutorial, you should have a basic understanding of JavaScript. But even if you are a beginner, you can still follow along and learn as you go.

In this article, we'll simplify a couple of steps. For more detail, you can also watch the extended tutorial on YouTube . In the YouTube version, we also cover how to make the buildings destructible, how to animate the hand of the gorilla to follow the drag movement while aiming, have nicer graphics, and we add AI logic, so you can play against the computer.

If you got stuck, you can also find the final source code of the game we are about to create on GitHub .

Table of Contents:

Background on the game, project setup, overview of the game logic, how to draw the scene, how to turn the coordinate system upside down, how to draw the game elements, how to fit the size of the city to the browser window, how the gorilla can throw the bomb, how to animate the incoming bomb.

Gorillas is a game from 1991. In this game, two gorillas are standing on the top of randomly generated buildings and take turns throwing explosive bananas at each other.

In each round, the players set the angle and velocity of the throw, and keep refining it, until they hit the other gorilla. The flying banana bomb is affected by gravity and the wind.

Screenshot-2024-01-07-at-22.58.23-1

We are going to implement a modern version of this game. The original game did not support a mouse. Every round, the players had to type in the angle and the velocity with a keyboard. We are going to implement it with mouse support, and nicer graphics.

You can try out the extended version of the game on CodePen . Give it a try before we get into it.

To implement this game, we are going to have a simple HTML, CSS, and JavaScript file. You can break down the JavaScript logic into multiple files if you want, but for the sake of simplicity, we have everything in one place.

Because we're using plain JavaScript and don’t use any libraries and third-party tools, we don’t need any compilers or builders. We can run things directly in the browser.

To simplify the process, I recommend installing the Live Server VS Code extension. With this extension installed, you can simply right-click the HTML file and select ‘Open with Live Server’. This will run a live version of the game in the browser.

This means we don’t have to hit refresh in the browser every time we make a change in the code. It’s enough that we save the changes in the file and the browser will refresh automatically.

Screenshot-2024-01-18-at-21.29.22-1

Before we get to the details, let's walk through the main parts of the game.

The game is driven by the game state . This is a JavaScript object that serves as metadata for the game. From the size of buildings to the current position of the bomb, it includes many things.

The game state includes things like whose turn it is, are we aiming now, or is the bomb already flying in the air? And so on. These are all variables that we need to keep track of. When we draw the game scene, we'll draw it based on the game state.

Then we have the draw function. This function will draw almost everything we have on the screen. It paints the background, the buildings, the gorillas, and the banana bombs. This function paints the entire screen from top to bottom every time we call it.

We are going to add event handling to aim the bombs and we'll implement the throwBomb function that kicks off the animation loop. The animate function moves the bombs across the sky.

This function will be responsible for calculating the exact position of the bomb as it flies through the air at every animation cycle. On top of that, it also has to figure out when the movement ends. With every movement, we check if we hit a building or an enemy, or if the bomb got off-screen. We’ll add hit detection as well.

Now let's walk through our initial files.

The initial HTML file

Our initial HTML file will be very simple. In the header, we'll add a link to our stylesheet and our JavaScript file. Note that I’m using the defer keyword to make sure the script only executes once the rest of the document is parsed.

In the body, we'll add a canvas element. We are going to paint on this element with JavaScript. Almost everything we can see on the screen will be in this canvas element. Here's the code:

Later we are going to add more things into this file. We'll add info panels to show the angle and velocity of the current throw. But for now, that’s all we have.

The initial CSS file

Initially, our CSS is also very simple. We can’t style anything inside the canvas element, so here we only style the other elements we have.

‌Later, when we add more elements in HTML, we will also update this file. For now, let’s make sure that our canvas can fit the whole screen. By default, browsers tend to add a little margin or padding around the body. Let’s remove that.

The Main Parts of Our JavaScript File

Most of the logic will be in our JavaScript file. Let's walk through the main parts of this file, and define a few placeholder functions:

  • We declare the game state object and a bunch of utility variables. This will contain the metadata of our game. For now, it's an empty object. We will initialize its value when we get to the newGame function.
  • Then we have references to every HTML element that we need to access from JavaScript. For now, we only have a reference to the <canvas> element. We access this element by ID.
  • We initialize the game state and paint the scene by calling the newGame function. This is the only top-level function call. This function is responsible for both initializing the game and resetting it.
  • We define the draw function that draws the whole scene on the canvas element based on the game state. We will draw the background, the buildings, the gorillas, and the bomb.
  • We set up event handlers for the mousedown , mousemove , and mouseup events. We are going to use these for aiming.
  • The mouseup event will trigger the throwBomb function that kicks off the main animation loop. The animate function will manipulate the state in every animation cycle and call the draw function to update the screen.

‌We will have a couple more utility functions, but they are less important. We'll discuss them as we go.

Game Phases

In the next step, we'll set up our initial game state . Before we get to the different parts of the state, let's talk about one of its most important properties: the game phase property.

Screenshot-2024-01-21-at-16.27.06-3

The game has three different phases. The game starts in the aiming phase, when the bomb is in the hand of a gorilla and the event handlers are active. ‌‌‌‌Then once you throw the bomb, the game moves on to the in flight phase. In this phase, the event handlers are deactivated and the animate function moves the bomb across the sky. We also add hit detection to know when should we stop the animation.

These two game phases repeat each other over and over again, until one of the gorillas hits the other. Once we hit the enemy, the game moves on to the celebrating phase. We draw a winning gorilla, show the congratulations screen, and a button to restart the game.

How to initialize the Game

The game is initialized by the newGame function. This resets the game state , generates a new level, and calls the draw function to draw the whole scene.

Let’s walk through what we have initially in the state object:

  • First, we have the game phase property that can be either aiming , in flight , or celebrating .
  • Then, the currentPlayer property tells us whose turn it is – the player on the left or the player on the right.
  • The bomb object describes the bomb’s current position and its velocity. Its initial position has to be aligned with the second building so we only set it once the level is generated.
  • The buildings array defines the position and size of the buildings that appear on the screen. We generate the metadata of the buildings with a utility function that we'll discuss later.

‌We'll discuss the utility functions used above ( generateBuildings and initializeBombPosition ) in the next chapter as we draw the buildings and the bomb. For now, let's just add some placeholder functions to make sure we don't get an error from JavaScript.

Now that we have a skeleton of our application and we've initialized some of the states, let’s switch gears and start drawing on the canvas as we fill in the missing pieces of the state.

The draw function paints the whole canvas based on the state. It draws the background and the buildings, draws the gorillas, and draws the bomb. The function can also draw different gorilla variations depending on the state. The gorilla looks different while aiming, celebrating, or waiting for impact.

We will use this function both for painting the initial scene and throughout our main animation loop.

For the initial paint, some of the features we cover here won't be necessary. For instance, we'll also cover how to draw the celebrating gorilla, while we'll only see that once the game is over. But we'll still cover it because this way we won’t have to get back to this function once we start animating the state.

Everything we draw in this function is based on the state, and it doesn't matter to the function if the game is in the initial state, or if we are further into the game.

We defined a <canvas> element in HTML. How do we paint things on it?

In JavaScript first, we get the canvas element by ID. Then we set the size of the canvas to fill the whole browser window. And finally, we get its drawing context.

This is a built-in API with many methods and properties that we can use to draw on the canvas. Let's see a few examples of how to use this API.

Example: Drawing a Rectangle

Let’s look at a few quick examples. These are not part of our game yet, they'll just serve as an introduction.

The most basic thing we can do is to fill a rectangle.

Screenshot-2024-01-21-at-23.00.23-1

With the fillRect method, we specify the top left coordinate of our rectangle (200, 200), and we set its width and height (440, 320).

By default, the fill color is going to be black. We can change it by setting the fillStyle property.

The way canvas works is that we have to set up drawing parameters before we paint, and not the other way around. It’s not like we paint a rectangle, and then we can change its color. Once something is on the canvas, it stays as it is.

You can think of it like a real canvas, where you also pick the color with your brush before you start painting with it. Then once you've painted something you can either cover it, by painting something over it, or you can try to clear the canvas. But you can’t change existing parts, really. That’s why we set the color here up front and not afterward.

We are going to draw rectangles to fill the background and to show the buildings.

Screenshot-2024-01-21-at-19.30.36

Example: Filling a Path

We can of course draw more complicated shapes as well. We can define a path, like this:

Screenshot-2024-01-21-at-23.01.23-1

Paths start with the beginPath method and end with either calling the fill or the stroke method – or both. In between, we build the path by calling path-building methods.

In this example, we draw a triangle. We move to the 300,300 coordinate with the moveTo method. Then we call the lineTo method to move to the right side of our shape. And then we continue the path, by calling the lineTo method again to 300,400 .

None of this would be visible if we didn’t end with the fill method to fill the path we just built.

We are going to fill paths to draw our gorilla and our bomb.

Screenshot-2024-01-19-at-16.41.19-4

‌Example: Drawing a Stroke

In a very similar way, we can also draw a line. Here, we'll start with the beginPath method again. We'll also build up the shape with a moveTo and two lineTo methods. The coordinates here are the same. But in the end, we don’t call the fill but the stroke method. This, instead of filling the shape, will draw the line we built.

Screenshot-2024-01-21-at-23.02.34-1

Strokes have different styling properties. Instead of the fillStyle property, we set strokeStyle . To this property – and also to fillStyle – we can assign any color value that is valid in CSS. To set the line width we use the lineWidth property.

We can also build more complex paths. In the example below, we draw a curve. We are going to cover this in a bit more detail when we draw the arms of the gorillas.

Screenshot-2024-01-21-at-23.05.04-1

We are going to use the stroke method to draw the arms and the face of the gorilla.

Screenshot-2024-01-19-at-17.06.58-2

‌Now that we're finished with this introduction, let’s go back to our game and see what’s inside the draw function.

When we use canvas, we have a coordinate system with the origin at the top-left corner of the browser window that grows to the right and downwards. This is aligned with how websites work in general. Things go from left to right and top to bottom. This is the default, but we can change this.

Screenshot-2024-01-21-at-23.09.35-1

When we talk about games, it is more convenient to go from the bottom to the top. For instance, when we draw buildings, they can start at the bottom, and we don’t have to figure out where the bottom of the window is.

We can use the translate method to shift the entire coordinate system to the bottom-left corner. We just need to move the coordinate system down along the Y-axis by the size of the browser window.

Once we do this, the Y-coordinate is still growing downwards. We can flip it using the scale method. Setting a negative number for the vertical direction will flip the entire coordinate system upside down.

Screenshot-2024-01-21-at-23.09.32-1

‌Now let's implement the draw function. One of the first things we do is calling the translate and the scale methods to flip the coordinate system upside down.

We have to do this before we paint anything on the canvas because the translate and scale methods do not actually move anything on the canvas. If we painted anything on the canvas before, it would stay as it was.

Technically these methods change the transformation matrix. You can think of it as changing the coordinate system. Anything we paint after these methods will be painted according to this new coordinate system.

We also need to restore these transformations once we draw by calling the restore method. The restore method comes in a pair with the save method. save serves as a checkpoint that the restore method can get back to.

It's a common practice to start a drawing block by calling the save method and ending it with the restore method when we use transformations in between.

We need to call these two functions because the translate and scale methods accumulate. We are going to call the draw function multiple times. Without the save and restore methods, the coordinate system would keep on moving downwards each time we call the draw function, and it would eventually get completely off-screen.

Drawing the entire scene includes many parts. We'll break it down into separate draw functions. Now let’s start drawing by implementing these functions:

How to draw the background

When we draw on a canvas, the order matters. We'll start with the background, then we'll go layer by layer. In our case, the background is a simple rectangle.

Screenshot-2024-01-30-at-16.00.14

We draw this rectangle the same way we did it in our introduction. First, we set the fill style, then we draw a rectangle with the fillRect method. Here we set the starting coordinates in the corner and set the size to fill the whole browser window.

We could also add a moon to the sky. Unfortunately, there's no fill circle method that would easily do this, so we'll skip it for now. On CodePen you can find a version that also draws a moon in the drawBackground function.

How to draw the buildings

Drawing the buildings has two parts. First, we need to generate metadata for the buildings when we initialize the level. Then we implement the drawBuildings function that paints the buildings based on this metadata.

Screenshot-2024-01-19-at-17.02.52-1

Buildings Metadata

In the newGame function, we called the generateBuildings function to initialize the buildings property in our game state . We haven't implemented this function yet.

‌Let's see how this function works. Each building is defined by its x position, its width , and its height .

The x coordinate is always aligned to the previous building. We check where the previous building ends, and we add a little gap. In case there is no previous building – because we're adding the first one – then we start at the beginning of the screen at 0.

Then the function generates a random building width within a predefined range. We set the minimum and maximum width, and pick a random number in between.

We generate a random building height in a similar way with one difference: the height of a building also depends on whether a gorilla is standing on top of it or not.

If a gorilla is standing on top of the building, then the height range is smaller. We want to have relatively higher buildings in between the two gorillas so that they can’t just see each other in a straight line.

We'll know if a gorilla is standing on the building because they always stand on top of the same buildings. The second one from the left, and the second to last. If the building index matches these positions, we set the height based on a different range.

Then we push these three values as an object into the buildings array, and at the final line we return this array from the function. This will set be buildings array in our game state .

How to draw the the buildings

Now that we have the metadata for the buildings, we can draw them on the screen.

The drawBuildings function is a very simple one. We iterate over the array we just generated and draw a simple rectangle for each. We use the same fillRect method we used to draw the sky. We call this function with the attributes of the building (the Y position is 0 because the building starts at the bottom of the screen).

Once we are done with this, we should see a line of buildings. The metadata is regenerated every time we start the game. Every time we refresh the browser window, we see a different background.

Screenshot-2024-01-19-at-16.57.16-1

‌How to draw the gorillas

Drawing the gorillas is one of the most complicated and most fun parts of this game. Finally, we are not just drawing rectangles – we're drawing paths.

Screenshot-2024-01-19-at-17.06.58-1

Gorillas also have different variations depending on the game state. The gorilla looks different while aiming, waiting for the incoming bomb, and celebrating after a successful hit.

In the draw function, we call the drawGorilla function twice. We draw two gorillas: one on the second rooftop and one on the second to last rooftop. They are mostly identical, but they mirror each other while aiming. When the left one is aiming, it raises its left hand, and when the right one is aiming, it raises its right hand.

‌We'll break down drawing the gorilla into multiple steps as well. We'll use different functions to draw the main body, to draw the arms, and to draw the face of the gorilla.

To make things easier, we'll translate our coordinate system again. We translate the coordinate system to the middle of the rooftop the gorilla stands on. This way we can draw both gorillas the same way. We only need to translate the origin of our coordinate system to a different building.

Screenshot-2024-01-30-at-16.58.41

‌As an argument, the drawGorilla function receives which player are we currently drawing. To draw the gorilla one on the left, we translate to the top of the second building, and to draw the one on the right we translate to the top of the second to last building.

‌Because we're using the translate method, this function starts with saving the current coordinate system and ends with restoring it.

Now let's look into the functions that draw the different parts of a gorilla.

How to draw the body of the gorilla

We draw the body of the gorilla as a path. We drew a path in our introduction to drawing on a canvas. We use the moveTo and a bunch of lineTo methods to draw the main part of the gorilla.

We set the fill style to black, and then we begin a path. We move to a coordinate in the middle and then we draw straight lines to draw the silhouette of the gorilla. Once we're finished, we fill the shape with the fill method.

Screenshot-2024-01-19-at-16.41.19-3

In case you are wondering how I came up with these coordinates, I actually started with an initial sketch with pen and paper. I tried to estimate the coordinates, tried them with code, and then adjusted them until they started getting the right shape. Of course, you might have other methods as well.

How to draw the arms of the gorilla

While the body was a relatively simple part of the gorilla, the hands are a bit more complicated. They come in different variations and we draw them as a curve.

Let’s start with the left arm. The main part of this is actually only two lines. We'll use the moveTo method to move to the shoulder of the gorilla, then from there, we'll draw the arm as a quadratic curve with the quadraticCurveTo method.

A quadratic curve is a simple curve with one control point. As the curve goes from the starting point (which we'll set with moveTo ), the curve bends towards this control point (set as the first two arguments of the quadraticCurveTo method) as it reaches its end position (set as the last two arguments).

Screenshot-2024-01-19-at-17.33.01-1

What makes this function complicated is that it has two variations of the same curve. By default, the hands go down next to the body (second case above).

If we are in the aiming phase, the currentPlayer is player number 1, and we are drawing player 1, then the left hand goes up (first case above). The left hand also goes up in case the we draw the celebrating gorilla (also first case above).

In these cases, we start the from the same point (the curve starts with the same moveTo method), but we set different coordinates for the control point and end point of the curve.

We draw the hands as strokes. So instead of ending the path with the fill method, we use the stroke method instead.

We also set it up differently. Instead of using the fillStyle property, here we set the color with strokeStyle and give thickness to the arm with the lineWidth property.

Screenshot-2024-01-19-at-16.44.18-1

Drawing the right arm is the same, except the horizontal coordinates and some conditions are flipped. We could merge these two functions, but for clarity, I kept them separate.

As a result, our gorillas should start to gain shape. They still don’t have a face, but they have hands now. And to reflect our game state, the one on the left has his hands up, preparing to throw the bomb.

You can test our solution by changing the game state. You can change the currentPlayer and the game phase properties to see the different variations.

How to draw the face of the gorilla

The face of the gorilla comes together from a few straight lines. We'll draw the two eyes and the mouth as a straight line. For each, we'll use pair of moveTo and a lineTo method. Because each line segment uses the same strokeStyle and lineWidth , we can draw them as one single path.

Screenshot-2024-01-19-at-17.08.58

With this, we have our finished gorillas with all the variations. There’s only one thing that’s missing from the screen: the banana bomb.

How to draw the bomb

Now we'll draw the bomb. The bomb is going to be a simple circle. But before we get to draw it, first we have to figure out where it is.

How to initialize the bomb’s position

If we look back at our newGame function, we can see that the metadata of the bomb has a position and a velocity. The position so far is still undefined . Before we get to drawing the bomb, first let’s figure out its position.

‌At the end of the newGame function, we also call the initializeBombPosition function before drawing the scene. Let’s implement this function.

The initializeBombPosition places the bomb in the hand of the gorilla that throws the bomb this turn. We have to call this function after we generate our building metadata because the bomb’s position depends on the position of the gorilla, and that depends on the building it stands on.

First, we look up which building we need to align with. If it’s the first player’s turn, then the bomb has to be in the left hand of the gorilla on the left. And if it’s the second player’s turn, then it has to be in the right hand of the gorilla on the right.

First, we'll calculate the midpoint of the rooftop we need ( gorillaX and gorillaY ), then offset the position to match the left or right hand of the gorilla.

Screenshot-2024-01-30-at-17.00.32

We'll also initialize the velocity again here. Later we are going to call this function at the beginning of every turn and then we need it to initialize these values.

Now that the bomb is in the right place, let’s draw it. Unfortunately, we don’t have a simple fill circle method, as we have in the case of rectangles. We have to draw an arc instead.

An arc method can be called as part of a path. We'll start with the beginPath method and end with the fill method.

The arc method has a lot of properties. This might look a bit scary, but we only need to focus on the first 3 when drawing circles:

  • The first two arguments are x and y , the center coordinates of the arc. We'll set them to match the position of the bomb that we know from the state .
  • The third argument is the radius . Here we'll set it to 6.
  • Then the last two arguments are the startAngle and the endAngle of the arc in radians. Because here we want to have a full circle and not an arc, we'll start with 0 and end at a full circle. A full circle in radians is two times Pi.

If these last two properties are confusing, don't worry about it. What's important is that when we draw circles, they are always 0 and 2 * Math.Pi .

Screenshot-2024-01-19-at-17.08.58-1

Now we have everything on the screen. We drew the background, the buildings, the gorillas, and the bomb. But things are not centered on the screen. Let’s fix that.

So far, we've aligned everything to the left side of the screen. Because the size of the buildings is random, the entire size of the city might be shorter or wider than the size of the browser window. It could even happen that we don’t see the second gorilla because it’s entirely off-screen. Or if the browser window is too wide, then we have a huge gap on the right side of the window.

To fix this, let’s match the size of the city with the width of the browser window.

To do this, let’s add a scale property to our state. In the newGame function, let’s add the scale property to the state object, and call a new function named calculateScale to set its value. This function call has to come after we generate our buildings because the scaling depends on the size of the city. It also has to come before we initialize the bomb position, because later that will depend on the scaling.

The calculateScale function is relatively simple. We calculate the total width of the city and divide the inner width of the browser window by this value. This will give us a ratio. It will tell how the width of our city relates to the width of the browser window.

Screenshot-2024-01-19-at-17.42.09-1

Then we have to use this new scale property at a few places. The most important is to change the scaling of the entire game in the draw function.

At the beginning of this function – where we flip the coordinate system – now we have another scale method call that applies this scaling. Because this is at the beginning of the draw function, everything we draw after this will be scaled.

‌And finally, we need to adjust how we draw our background. Earlier when we drew the background, we filled the entire screen by setting its width and height based on the window’s innerWidth and innerHeight properties. Now as everything is scaled, they don’t match the size of the browser window anymore. Whenever we use these properties, we need to adjust them by our scaling factor.

Screenshot-2024-01-19-at-17.45.05-2

How to resize the window

Now the 8 buildings we drew fit nicely with the size of our screen – but what happens if we resize the window? We are going to have the same problems we had before.

As a finishing touch, let’s handle the window resize event. This event handler resizes the canvas element to fit the new window size, recalculates the scaling, readjusts the position of the bomb, and redraws the entire scene based on the new scaling.

Readjusting the bomb position does not make a difference yet, but later we will update this function and it will rely on the new scaling.

So far we've just drawn a static scene. It’s time to make things interactive.

Throwing the bomb has two different parts. First, we have to aim. We grab the bomb with the mouse and drag it to set the throwing angle and the velocity. While dragging, we need to display the angle and velocity in info panels at the top of the screen. We'll also paint the throw trajectory on the screen. This is the aiming phase.

Screenshot-2024-01-21-at-16.27.06-4

Then once we release the mouse, the bomb flies across the sky. We are going to have an animation loop that moves the bomb across the sky. This is the in flight phase.

Screenshot-2024-01-21-at-16.27.09-4

‌In this phase, this animation loop will also include hit detection. We need to know if the bomb hit the enemy, a building, or went out of the screen. If we hit a building, or the bomb goes off-screen, we switch players and get back to the aiming phase again. If we hit the enemy, then we get to the celebrating phase. We then draw the celebrating variant of the current player’s gorilla and we show the congratulations screen.

Screenshot-2024-01-21-at-16.27.11-4

Now let’s go through these parts in detail.

In the aiming phase, we can drag the bomb to set its angle and velocity – like we throw a bird in Angry Birds. We are going to set up event handlers for this.

While aiming, we are going to show the current angle and velocity at the top-left or the top-right corner of the screen (depending on the player). We are also going to draw the throw trajectory on the screen to show in which direction the bomb will fly.

Info panels showing the angle and the velocity

In the original 1991 game, we had to type in the angle and velocity with the keyboard, as it had no mouse support. Here, we are going to aim with the mouse – but we still add the same UI elements on the screen. We'll update these fields as we are moving the mouse while dragging.

Screenshot-2024-01-21-at-16.02.31-2

We'll add these info panels in HTML. We could draw these text fields on the canvas as well, but it might be easier to use plain old HTML and CSS.

We'll add two divs, one for player 1 and one for player 2. Both include a header with the player number. We'll also add two paragraphs for the angle and the velocity. The info panels must come after the canvas element because otherwise, the canvas would cover them.

We'll assign two different IDs and appropriate class names. We'll use these names both for styling and for accessing these elements in JavaScript.

In the CSS, we'll move these panels into position and set some styling for the texts. We also want to ensure the user cannot select the text on the screen. Otherwise, you might end up accidentally selecting these text fields while aiming.

Then finally, in JavaScript we'll add some references to angle and velocity fields somewhere at the beginning of our file.

When we add event handling, we'll update the content of these elements with the mouse movement. For now, let's just leave it like that.

The grab area of the bomb

We are going to set up event handlers to drag the bomb. But what can we even drag? The whole canvas element is one single element. We could attach an event handler to it, but then we could start dragging the bomb by clicking anywhere on the screen. We don’t want that.

Screenshot-2024-01-30-at-17.04.21

Instead, we define another element in HTML that will serve as the grab area. We add the bomb-grab-area element. This is not going to include the bomb that we see on screen – that is already part of the canvas – but it will be an invisible area around it, serving as an event target.

We'll also add some styling to it with CSS. We want it to have an absolute position and to be an invisible circle with a slightly bigger radius than the bomb (so it’s easier to grab it). We can set the exact position in JavaScript.

We'll also change the cursor once the mouse is on top of it to grab . While this element is invisible, you can still notice that your mouse is at the right place by the changing cursor.

Then finally in JavaScript, we need to do two things before we set up event handling. First, get a reference to it somewhere at the beginning of the file.

Then we need to move it to the correct position. We already have a function that initializes the bomb position on the canvas. We can extend the initializeBombPosition function to position this HTML element as well.

We'll move the grab area to the same place as the bomb on the screen, but its coordinates are a bit different. The content of the canvas is scaled, but any other HTML element is not. We need to adjust the coordinates by the scaling. Also, note that we'll set the grabAreaRadius variable to be half of the size we defined for this element in CSS.

‌Once we've added this, we won’t see any difference on the screen, because this item is invisible. But once we hover over the bomb, we'll see that the cursor changes to grab.

Event handling

Now with everything set up, we can finally set up the event handling. This is going to be a simple drag-and-drop implementation where we listen to the mousedown , mousemove , and mouseup events.

First, we'll set up some top-level variables somewhere at the beginning of the file. We have a boolean variable that tells us if we are currently dragging or not, and two variables that tell us where the drag started, in case we are dragging.

We add the first event handler for the mousedown event on the grab area of the bomb. Being able to set this event handler is the reason we added the bomb-grab-area element earlier.

This event handler only does anything if we are in the aiming phase. If that is true, we set the isDragging variable to true, save the current mouse position, and set the mouse cursor permanently to grabbing (so that the cursor stays as grabbing even if we leave the grab area).

Then we'll add an event handler for the mousemove event. Note that now the event target is not the grab area of the bomb, but the window object. This is because while we are dragging we can easily move the mouse outside the grab area – or even outside the browser window – and we still want this event handler to work.

This event handler first checks if we are currently dragging. If not, then it doesn’t do anything. If we are dragging, then it calculates the delta of the mouse position since the mousedown event and sets it as the velocity of the bomb.

When we release the mouse, we want the bomb to move the opposite way as we drag the mouse, so we need to set the horizontal and vertical velocity with a negative sign. But then with a double twist, we switch back the vertical velocity (the Y coordinate), to have a positive sign because we flipped the coordinate system.

Event handlers still assume that the coordinate system grows downwards. Within the canvas, it goes in the opposite direction.

This event handler also calls a utility function to show the angle and the velocity at the info panels we just added in HTML. Then we call the draw function again. For now, calling the draw function here does not change anything on the screen, but soon we will update the drawBomb function to draw the throwing trajectory.

The setInfo button updates the UI elements we defined in HTML. We already have references to these elements at the top of our file, so here we only need to update their content as we drag the bomb.

‌But there is a bit of a complication. From the mousemove event, we got the vertical and horizontal components of the velocity. But on the UI we want to display the angle and the total velocity of the throw. We need to use some trigonometry to calculate these values.

Screenshot-2024-01-19-at-20.56.06-1

‌For the velocity, we'll calculate the hypotenuse of an imaginary triangle made up of the horizontal and vertical components of the velocity. For the angle , we'll use the arc sine function (the inverse of the sine function). We'll also make sure to update the correct info panel depending on whose turn it is, and we'll round the values.

At this point, while the scene should stay the same as it is, the values in the left info panel should update as we drag.

Finally, we'll add the event handler for the mouseup event, again on the window object. It only does anything if we are currently dragging. Then it notes that we are not dragging anymore, changes the cursor back to default, and calls the throwBomb function.

The throwBomb function switches the game phase to in flight and kicks off the animation of the bomb. We are going to cover this function in the next chapter, but before we get there, let's update one more thing.

How to draw the throw trajectory

While we are aiming, we can also draw the throwing trajectory. The throwing trajectory is the visualized form of the velocity and the angle.

Screenshot-2024-01-21-at-16.27.06-5

‌To do this, let’s go back to the drawBomb function and make some changes. If we are in the aiming phase, we'll draw a straight line from the center of the bomb to the velocity.

We'll draw this line as a path, as we did before. We'll start it with the beginPath method and end it with the stroke method. In between we'll use the moveTo and the lineTo method.

There’s one new thing here though: the setLineDash method. With this setting, we can draw a dotted line. We'll set that after every 3 pixels of line, and we want to have 8 pixels of gap. The 3-pixel dash matches the lineWidth , so the dashes will look like dots.

Now we've finished everything about the aiming phase. It’s time to throw the bomb.

Once we release the mouse after the aim, the bomb flies across the sky. We'll add an animation loop that moves the bomb, calculates its position with every animation cycle, and checks if we hit something.

Earlier, we saw that the event handler of the mouseup event ends with calling the throwBomb function. Let's implement this function.

This function first kicks off the in flight phase. Then it resets the previousAnimationTimestamp variable. This is a new utility variable needed for the animation loop. We'll cover it in a second. Then we start the animation loop, by calling requestAnimationFrame with the animate function as an argument. Let’s dig deeper into this animate function.

The animation loop

The animate function moves the bomb and calls the draw function to repaint the screen over and over again until we hit the enemy, a building, or the bomb goes off the screen.

By calling this function with requestAnimationFrame the way you see below, the animate function will run around 60 times every second. The constant repainting of the screen will appear as a continuous animation. Because this function is running so frequently, we're only moving the bomb little by little each time.

Gorillas-Keynote.006

‌This function keeps track of how much time has passed since its last call. We are going to use this information to precisely calculate how much should we move the bomb.

Functions invoked with the requestAnimationFrame function receive the current timestamp as an attribute. At the end of every cycle, we save this timestamp value into the previousAnimationTimestamp variable, so that in the next cycle we can calculate how much time has passed between two cycles. In the code below, this is the elapsedTime variable.

The first cycle is an exception because, at that point, we didn’t have a previous cycle yet. At the beginning of each throw, the value of previousAnimationTimestamp is undefined (we made sure it's undefined in the throwBomb function). In this case, we skip a render and we'll only render the scene on the second cycle, where we already have all the values we need. This is the part at the very beginning of the animate function.

‌Inside the function, we are going to move the bomb every cycle by calling the moveBomb function. We'll pass on the elapsedTime variable so it can precisely calculate by how much should it move the bomb.

In every cycle, we also detect if we hit an enemy, or if we missed and the bomb hit a building or got off screen. If none of that happens, then we need to repaint the scene and request another animation frame to continue the animation loop. But if we missed the enemy or got a hit, then we'll stop the animation loop by returning from the function. By returning early from the function, we never reach the last line, which would trigger the next animation cycle. The loop stops.

How to move the bomb

We move the bomb by calling the moveBomb function in the animation loop. This function calculates the new x and y position of the bomb in every cycle.

The new x and y values are calculated based on the velocity. But the vertical and horizontal velocity can be a relatively high number.

We don’t want the bomb to cross the screen with lightning speed, so to slow down the movement we'll multiply the values by a very small number. This multiplier also takes into consideration the elapsed time, so the animation will look consistent even if the animation cycles are not triggered at equal intervals.

With every cycle, the velocity of the bomb is also adjusted by gravity. We'll gradually increase the motion of the bomb towards the ground. We'll also adjust the vertical velocity by a small constant that also depends on the time passed.

Hit detection

Our animation loop keeps moving the bomb to infinity. But once we hit a building, the enemy, or the bomb got off-screen, we should stop this motion.

We need to detect these cases and handle them appropriately. If the bomb gets off-screen or we hit a building we should move on to the next player and get back to the aiming phase. In case we hit the enemy, we should move on to the celebrating phase and announce the winner.

In all these cases, we can stop the loop by returning early from the animate function. In these cases, the animate function does not reach its last line which would trigger another animation cycle.

How to improve hit detection precision

While we already slowed down the movement of the bomb to have a nice animation on screen, the bomb can still be a bit too fast for hit detection.

When the bomb is in flight, it can move by more than 10 pixels at a time. If we do hit detections only once per animation cycle, then we are completely blind to what happens during these 10-pixel movements. The bomb can easily go through parts of the gorilla without us noticing that we should have had a hit, or go through the corner of a building without any impact.

Screenshot-2024-01-19-at-23.19.47-1

To solve this, we are not only going to do hit detection once per every animation cycle, but multiple times. We'll break down every movement into smaller segments, and with every tiny movement, we need to check if we have a hit.

We'll still render the scene once per animation cycle, but before calling the draw function, we'll break down the movement into 10 segments with a loop.

Screenshot-2024-01-30-at-17.10.02

If we break down each animation cycle into ten segments, that also means that now we call the moveBomb function ten times more. We need to slow it down even more. Because this function moves the bomb according to the time passed, it’s enough if we divide its time attribute also by ten.

This way the bomb moves across the sky with the same speed, but we have ten times more precision with hit detection. In the example below, we wrap calling the moveBomb function and the hit detection logic into a for loop.

In the example above we've also introduced some utility functions for hit detection. In the next steps let’s implement these functions.

How to detect if the bomb is off the screen

We've missed the target if we reach the edge of the screen or if we hit a building. Checking if we've reached the edge of the screen is a very easy thing to do.

Screenshot-2024-01-30-at-17.07.56

‌We only need to check if the bomb went out on the left side, the bottom, or the right side of the screen. If the bomb goes through the top of the screen, that’s okay. Gravity will eventually pull it back.

Note that because of the scaling, the right side of the screen is not the same as the window’s innerWidth value. We have to adjust that by the scaling factor.

If the bomb went out of the screen, we return true to signal to the animate function that we can stop the animation loop.

How to detect if the bomb hit a building

We also miss the target if the bomb hits a building. We can iterate over the buildings array and check if any side of the bomb is within the rectangle of the building. We need to check that:

  • The right side of the bomb is on the right of the left side of the building,
  • The left side of the bomb is on the left of the right side of the building,
  • And that the bottom of the bomb is below the top of the building.

Screenshot-2024-01-19-at-22.59.23-1

If all this is true, then we know that the bomb hit the building. If we get a hit, the function ends with returning true. This will also signal to the animate function that we can stop the animation loop.

How to detect if the bomb hit the enemy

Now that we can detect if the bomb went off-screen and we have hit detection for buildings, it’s time to detect if we hit the enemy.

We are going to have a different approach this time. Detecting if we got a hit with traditional geometric calculations would be much more complicated, because the gorillas are not built with basic rectangles and circles.

Screenshot-2024-01-19-at-23.49.34-1

Instead, we can use the isPointInPath method that conveniently tells us if a point – in this case, the center of the bomb – is within a path.

This method tells us if a point is within the current or previous path. So before calling the method, we need to recreate the gorilla. The gorilla is not only one single path, so we have to test against the most relevant path, the main body of the gorilla.

Conveniently – and with some smart planning – we already have a function that paints the body of the gorilla as a single path. We call the drawGorillaBody function right before isPointInPath . But the drawGorillaBody function paints with coordinates relative to the rooftop of a building, so before calling it, we need to translate the coordinate system.

Depending on the current player, we'll calculate which building the enemy stands on, and translate the coordinate system to top of that. Because of this translation, we also use the save and restore methods.

Similarly, we can also detect if we hit one of the arms of the gorilla. The arms are drawn as a stroke, so in this case instead of isPointInPath we'll use the isPointInStroke method. This detection would not have worked if we did not increase the hit detection precision earlier, because the bomb could easily jump over the arm.

With this function, we have every piece of the hit detection. The animation loop stops in case we hit a building, the enemy, or the bomb gets off-screen. It’s time to handle what’s next in these cases.

How to handle the result of hit detection

Once we have proper hit detection, it's time to finally handle the cases when we hit a building, the enemy, or the bomb goes off-screen. We'll update the animate function one last time. The only thing new below is the code block of the two if statements inside the loop.

If we hit the edge of the screen or a building, that means we've missed the target. In this case, we'll switch players and get back to the aiming phase. We'll also re-initialize the bomb position to move it to the new player’s hand.

Screenshot-2024-01-20-at-00.39.59-1

Then we'll simply call the draw function to handle the rest. The beauty of this structure is that we only need to change the game state and the draw function can repaint the whole scene according to it.

Then we'll return from the animate function to stop the animation loop. The event handlers are active again (because we are back in the aiming phase), and the next player can take a shot.

If we hit the enemy, we need to switch to the celebrating phase. We'll announce the winner with a function that we are about to cover in the next section. Then we repaint the scene with a celebrating gorilla and return to stop the animation loop.

Screenshot-2024-01-19-at-23.49.34-2

‌To make sure our code does not throw an error, let's add a placeholder for the announceWinner function.

How to announce the winner

Once we hit the enemy, we should announce the winner.  For this, we'll add another info panel in HTML that includes who won the game and a restart button. At the bottom of the now-finished HTML file, you can find the congratulations panel.

Screenshot-2024-01-21-at-16.27.11-6

This panel is hidden by default and it only shows up at the end of the game. When it shows up, it should be in the middle of the screen. We'll update our CSS file according to this.

Note that we added display: flex to the body element with a few more properties to center everything on the screen. Then we set position: absolute for the congratulations element and hide it by default.

Then finally we can use this panel to announce the winner once the game ends in JavaScript. We already call the announceWinner function in our animate function so it’s time to implement it.

First, somewhere at the beginning of the file, we'll set up some references for the congratulations panel itself and the winner field.

Then in the announceWinner function, we'll set the content of the winner field to say the current player and show the congratulations panel.

With this piece, we finally can play the game until the end. We can aim, the bomb flies across the sky, and the gorillas take turns until one of them wins the game. The only missing piece is resetting the game for another round.

How to reset for another round

As a final finishing touch, let’s add an event handler for the 'New Game' button on our congratulations panel to be able to reset the game. We've already added a button with the ID new-game in our HTML.

In JavaScript first, we'll create a reference to this button and then add an event handler for it. This event handler simply calls the newGame function.

The newGame function should reset everything and generate a new level so we can start a new game. At this point, though, our newGame function does not reset everything. It does not reset the HTML elements we introduced in the meantime.

As a very last step, we'll make sure that the congratulations element is hidden once we start a new game, and reset the angle and velocity values in the left and right info panels to 0.

While we now have a full two-player game, we can do a lot more. On YouTube I also cover how to make the buildings destructible, how to animate the hand of the gorilla to follow the drag movement while aiming, and we spend more time adding detailed graphics. There's also a whole chapter on how to add computer logic to the game, so that you can play against the computer.

Check it out to learn more:

Subscribe to my channel for more JavaScript game development tutorials:

favicon_144x144

Full-stack web developer, coach, posting creative coding tutorials and games on YouTube and CodePen

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

DEV Community

DEV Community

Shawn2208

Posted on Sep 2, 2023

Building a Mini Text-Based Adventure Game: "Mini Zork" with HTML, CSS, JS

Ever played a text-based game? These games, which date back to the early days of computing, have always fascinated me with their simplicity yet immersive nature. Today, I'm going to introduce you to "Mini Zork", a simple text-based game built using HTML, CSS, and JavaScript.

  • The HTML Structure: The structure is straightforward. We have a terminal div with an output section for game feedback and an input section to receive commands from the player:
  • Game Logic with JavaScript:
  • Styling the Game with CSS: The game has a retro terminal look, achieved by simple CSS:
  • Play the Game: Once everything is set up, launch the HTML page in your browser and start your adventure! Try commands like 'look', 'go north', 'go south', etc. Navigate through the rooms and find the treasure.

Building a simple text-based game like "Mini Zork" is not only a fun project but also a great way to sharpen your web development skills. Feel free to extend the game by adding more rooms, challenges, or even NPCs. Enjoy coding and gaming!

Also i'm going to give you some ways of extending it.

More Rooms and Complex Maps:

Multi-layered Rooms: Introduce rooms that have multiple layers, such as basements or upstairs.

Interconnected World: Instead of a linear path, create loops where rooms can interconnect in multiple ways, making navigation a challenge.

Introduce Items and Inventory: Players can pick up or drop items, which might be crucial for solving certain puzzles or unlocking specific rooms. For example, finding a key in one room to unlock another room.

Add NPCs (Non-Player Characters): Introduce characters that provide hints, challenges, or trade items. Use an array or object to store their dialogues based on the player's progression.

Advanced Commands: Let players use more complex commands like use or talk to . Perhaps introduce a basic combat system where players can attack or defend.

Puzzles and Riddles: Require players to solve puzzles to advance. This could be in the form of riddles, number puzzles, or logic puzzles.

Save and Load System: Implement a local storage-based save system, so players don't have to start over every time they refresh the page.

Styling and Themes: Introduce different themes. Perhaps a retro neon theme for a sci-fi story or a sepia-toned theme for a wild west adventure. Add sound effects or background music for immersion.

Random Events: Introduce random events or encounters that provide an element of unpredictability to the game. Maybe there's a chance to find a rare item or encounter a mysterious character.

Have fun and extending these will improve your understanding.

Top comments (1)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

shinyvision profile image

Why is everything Javascript?

Rachel Snijders - Feb 20

ghostaram profile image

How to set and customize horizontal and vertical scrollbars with CSS

Felix Owino - Feb 7

hasanelsherbiny profile image

What Is Middleware?

Hasan Elsherbiny - Feb 15

msiatrak profile image

Securing API Keys in SwiftUI: A Practical Guide (Intro)

Mateusz Siatrak - Feb 16

Once suspended, shawn2208 will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, shawn2208 will be able to comment and publish posts again.

Once unpublished, all posts by shawn2208 will become hidden and only accessible to themselves.

If shawn2208 is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to Shawn2208.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag shawn2208:

shawn2208 consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.

Unflagging shawn2208 will restore default visibility to their posts.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

HTML Playground

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Introduction to game development for the Web

The modern web has quickly become a viable platform not only for creating stunning, high quality games, but also for distributing those games.

The range of games that can be created is on par with desktop and native OS counterparts. With modern Web technologies and a recent browser, it's entirely possible to make stunning, top-notch games for the Web. And we're not talking about simple card games or multiplayer social games that have in the olden days been done using Flash®. We're talking about 3D action shooters, RPGs, and more. Thanks to massive performance improvements in JavaScript just-in-time compiler technology and new APIs, you can build games that run in the browser (or on HTML5 -powered devices) without making compromises.

The HTML game platform

You can truly think of the Web as a better target platform for your game. As we like to say, "the Web is the platform." Let's take a look at the core of the Web platform:

The business case

As a game developer, whether you're an individual or a large game studio, you want to know why it makes sense to target the Web with your next game project. Let's look at how the Web can help you.

  • The reach of the Web is enormous; it's everywhere. Games built with HTML work on smartphones, tablets, PCs and Smart TVs.
  • Marketing and discoverability are improved. You're not limited to promoting your app on someone else's app store. Instead, you can advertise and promote your game all over the Web as well as other media, taking advantage of the Web's inherent linkability and shareability to reach new customers.
  • You have control where it matters: Payments. You don't have to hand over 30% of your revenues to someone else just because your game is in their ecosystem. Instead, charge what you want and use whatever payment processing service you like.
  • Again with more control, you can update your game whenever you want. No waiting breathlessly for approval while someone hidden within another company decides whether your critical bug fix will ship today or tomorrow.
  • Control your analytics! Instead of relying on someone else to make all the decisions about what analytics you need, you can collect your own — or choose the third party that you like the best — to gather information about your sales and your game's reach.
  • You get to manage your customer relationship more closely, in your own way. No more having customer feedback filtered through an app store's limited mechanisms. Engage with your customers the way you want to, without a middleman.
  • Your players can play your game anywhere, anytime. Because the Web is ubiquitous, your customers can check their game's status on their phones, tablets, their home laptops, their work desktops, or anything else.

Web technologies for game developers

For the tech folks, let's dig into the APIs the Web brings to the table that cater to game developers. Here's a thorough list to give you a taste of what the Web can do for you:

Send and receive any kind of data you want from a Web server like downloading new game levels and artwork to transmitting non-real-time game status information back and forth.

This simple API lets your game take over the entire screen, thereby immersing the player in action.

If you want your users to be able to use gamepads or other game controllers to work your game, you'll need this API.

Together, these two technologies let you build, style, and lay out your game's user interface. Part of HTML is the <canvas> element, which provides one way to do 2D graphics.

The <audio> element lets you easily play simple sound effects and music. If your needs are more involved, check out the Web Audio API for real audio processing power!

A powerful data storage API for maintaining user data on their own computer or device. A great way to save game state and other information locally so it doesn't have to be downloaded every time it's needed. Also useful to help make your game playable even when the user isn't connected to the Web (such as when they're stuck on an airplane for hours on end).

JavaScript, the programming language used on the Web, is blazing fast in modern browsers and getting faster all the time. Use its power to write the code for your game, or look at using technologies like Emscripten or Asm.js to easily port your existing games.

The Pointer Lock API lets you lock the mouse or other pointing device within your game's interface so that instead of absolute cursor positioning you receive coordinate deltas that give you more precise measurements of what the user is doing, and prevent the user from accidentally sending their input somewhere else, thereby missing important action.

Lets you build vector graphics that scale smoothly regardless of the size or resolution of the user's display.

JavaScript typed arrays give you access to raw binary data from within JavaScript; this lets you manipulate GL textures, game data, or anything else, even if it's not in a native JavaScript format.

This API for controlling the playback, synthesis, and manipulation of audio from JavaScript code lets you create awesome sound effects as well as play and manipulate music in real time.

Lets you create high-performance, hardware-accelerated 3D (and 2D) graphics from Web content. This is a Web-supported implementation of OpenGL ES 2.0.

The WebRTC (Real-Time Communications) API gives you the power to control audio and video data, including teleconferencing and transmitting other application data back and forth between two users. Want your players to be able to talk to each other while blowing up monsters? This is the API for you.

The WebSocket API lets you connect your app or site to a server to transmit data back and forth in real-time. Perfect for multiplayer gaming action, chat services, and so forth.

Workers give you the ability to spawn background threads running their own JavaScript code, to take advantage of modern, multicore processors.

HTML Tutorial

Html graphics, html examples, html references, html introduction.

HTML is the standard markup language for creating Web pages.

What is HTML?

  • HTML stands for Hyper Text Markup Language
  • HTML is the standard markup language for creating Web pages
  • HTML describes the structure of a Web page
  • HTML consists of a series of elements
  • HTML elements tell the browser how to display the content
  • HTML elements label pieces of content such as "this is a heading", "this is a paragraph", "this is a link", etc.

A Simple HTML Document

Example explained.

  • The <!DOCTYPE html> declaration defines that this document is an HTML5 document
  • The <html> element is the root element of an HTML page
  • The <head> element contains meta information about the HTML page
  • The <title> element specifies a title for the HTML page (which is shown in the browser's title bar or in the page's tab)
  • The <body> element defines the document's body, and is a container for all the visible contents, such as headings, paragraphs, images, hyperlinks, tables, lists, etc.
  • The <h1> element defines a large heading
  • The <p> element defines a paragraph

What is an HTML Element?

An HTML element is defined by a start tag, some content, and an end tag:

The HTML element is everything from the start tag to the end tag:

Note: Some HTML elements have no content (like the <br> element). These elements are called empty elements. Empty elements do not have an end tag!

Advertisement

Web Browsers

The purpose of a web browser (Chrome, Edge, Firefox, Safari) is to read HTML documents and display them correctly.

A browser does not display the HTML tags, but uses them to determine how to display the document:

View in Browser

HTML Page Structure

Below is a visualization of an HTML page structure:

Note: The content inside the <body> section will be displayed in a browser. The content inside the <title> element will be shown in the browser's title bar or in the page's tab.

HTML History

Since the early days of the World Wide Web, there have been many versions of HTML:

This tutorial follows the latest HTML5 standard.

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

IMAGES

  1. Snake game using HTML , CSS & java script

    html tutorial game

  2. A Complete Guide On How to Make HTML5 Games?

    html tutorial game

  3. Js13kGames Tutorial

    html tutorial game

  4. Create a Platformer Game with JavaScript

    html tutorial game

  5. Create A Mobile Educational Game With HTML5

    html tutorial game

  6. 35 How To Make A Javascript Game

    html tutorial game

VIDEO

  1. html tutorial html css javascript tutorial for beginners in hindi html full course html tags #shorts

  2. My JavaScript 2D Game

  3. Make interesting 🤔 Game using html

  4. Pure CSS Games

  5. I Created A Game Using HTML, CSS AND JavaScript

  6. Create a GAME Using Only HTML and CSS, The World's First NONJS Game! without single line of JS

COMMENTS

  1. HTML Game Example

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  2. How to build a game with HTML, CSS, and JavaScript

    First, we'll start with the game div. Select the element by its id, which is represented by the hash ( #) symbol. #game{ width: 500px; height: 200px; border: 1px solid black; margin: auto; } Next, we'll style our character div.

  3. How to Make a Game in HTML: A Step-by-Step Guide for Beginners

    Do you want to create your own online games using HTML? In this guide, you will learn how to make a game in HTML from scratch, with no coding experience required. You will discover the basic concepts, tools, and steps involved in game development, as well as some tips and tricks to make your game more fun and interactive. Whether you want to make a simple quiz, a platformer, or a shooter, this ...

  4. JavaScript Game Tutorial

    In this tutorial, you'll learn how to create a game that's inspired by Stick Hero - using plain JavaScript and HTML canvas. We are going to recreate Stick Hero, a mobile game published by KetchApp.

  5. Tutorials

    This tutorial shows how to create a 2D maze game using HTML, incorporating fundamentals such as collision detection and sprite placement on a <canvas>. This is a mobile game that uses the Device Orientation and Vibration APIs to enhance the gameplay and is built using the Phaser framework. 2D platform game with Phaser

  6. Introduction to HTML Game Development

    Introduction to HTML Game Development Advantages Games built with HTML work on smartphones, tablets, PCs and Smart TVs. Advertise and promote your game all over the Web as well as other media. Payments. Charge what you want and use whatever payment processing service you like. Update your game whenever you want. Collect your own analytics!

  7. How to Code a Simple Game and Host it on Your Website

    In this article, we'll be learning how to code a simple game using HTML, CSS, and JavaScript, and then host it on your website. The game we'll be coding is a classic word-guessing game - Melting Snowman! HTML, CSS, and JavaScript are some of the most classic languages for web development.

  8. Develop an HTML5 Game

    In this tutorial series you'll build a simple HTML5 game that will let you control a player with user input. The series will take you through the following steps: Set-up an HTML5 file with a canvas Learn how to draw shapes and text Create a game loop Animate objects and use easings Detect collisions and apply physics

  9. The Ultimate List of HTML5 Game Development Tutorials

    HTML5 Video Game Development Tutorials HTML5 is the standard language for everyone's favorite worldwide web. It was developed by W3C (World Wide Web Consortium). This is a great language to learn if you're looking to deliver applications across more than one platform. The latest and greatest version of HTML these days is HTML5.

  10. 2D breakout game using pure JavaScript

    In this step-by-step tutorial we create a simple MDN Breakout game written entirely in pure JavaScript and rendered on HTML <canvas>. Every step has editable, live samples available to play with so you can see what the intermediate stages should look like.

  11. The Complete Guide to Building HTML5 Games with Canvas and SVG

    To start building HTML5 games with Canvas and SVG, you need a text editor, a modern web browser for testing, and a basic understanding of HTML, CSS, and JavaScript. Text editors like Sublime Text ...

  12. Build A JavaScript Game Step-By-Step (Using HTML, CSS + JavaScript

    Build A JavaScript Game Step-By-Step (Using HTML, CSS + JavaScript) November 27th, 2023 Updated: January 25th, 2024 21 min read In This Tutorial: Step 1: Building the User Interface (UI) with HTML Step 2: Refining the User Interface (UI) with CSS Step 3: JavaScript - Player Selection Step 4: JavaScript - Computer Selection

  13. How To Make An HTML5 Game

    The Best Way to Learn to Code - 10 Steps Beginners Coding Success Guide Complete Guides Best Game Engines - Which Should You Use? Best Game Development Courses (Full List) How to Make an HTML5 Game Roblox Game Making Tutorials How to Make a Unity Game? How to Make a Mobile Game in Unity What is Python Programming?

  14. Creating a Tetris Game with HTML, CSS and JavaScript

    Creating a Tetris Game with HTML, CSS and JavaScript Learn how to create a Tetris game from scratch using JavaScript with this beginner-friendly guide. Build the game mechanics, levels, and scoring system step-by-step. Responsive Contact Form Design using HTML, CSS, and JavaScript: Step-by-Step with Source Code

  15. HTML5 Tutorials

    At the very least, this tutorial will teach you how to approach building and designing an Endless Runner game in HTML5. To view the full list, click here This page showcases useful tutorials for HTML5 game developers. We've ensured that they easy to pick up, learn and internalize.

  16. JavaScript Game Dev Tutorial

    Hunor Márton Borbély. In this JavaScript game tutorial, you'll learn how to create a modern version of the 1991 classic game Gorillas using plain JavaScript and the HTML canvas element. In this game, two gorillas throw explosive bananas at each other, and the first one to hit the other one wins the game. We'll build out the whole game from ...

  17. Create the Canvas and draw on it

    The HTML document structure is quite minimal, as the game will be rendered entirely on the <canvas> element. Using your favorite text editor, create a new HTML document, save it as index.html, in a sensible location, and add the following code to it:

  18. Building a Mini Text-Based Adventure Game: "Mini Zork" with HTML, CSS

    Today, I'm going to introduce you to "Mini Zork", a simple text-based game built using HTML, CSS, and JavaScript. The HTML Structure: The structure is straightforward. We have a terminal div with an output section for game feedback and an input section to receive commands from the player:

  19. HTML Tutorial

    Study our free HTML Tutorial » Watch our Video Tutorial » NEW Easy Learning with HTML "Try it Yourself" With our "Try it Yourself" editor, you can edit the HTML code and view the result: Example <!DOCTYPE html> <html> <head> <title> Page Title </title> </head> <body> <h1> This is a Heading </h1> <p> This is a paragraph. </p> </body> </html>

  20. Game Tutorial

    The HTML <canvas> element is displayed as a rectangular object on a web page: HTML Canvas The <canvas> element is perfect for making games in HTML. The <canvas> element offers all the functionality you need for making games. Use JavaScript to draw, write, insert images, and more, onto the <canvas>. .getContext ("2d")

  21. Game development

    HTML5 Game Engine List of the most popular HTML game frameworks along with their rating, features and samples. Tuts+ Game Development Tutorials and articles about game development in general. HTML5 Gamedev Starter Starter for the new game developers, a curated list of links to various useful resources around the web. js13kGames

  22. HTML Playground

    Learn and practice HTML with this online playground that offers instant live preview and console. You can create and share your own HTML projects using ready to use templates or from scratch. PlayCode.io HTML Playground is the best way to master HTML in a fun and interactive way.

  23. Infinite Craft

    Infinite Craft is a 2024 sandbox browser game developed by Neal Agarwal, in which the player starts with four elements—earth, wind, fire, and water—and combines them into people, astrological beings, and fictional characters. AI software, including LLaMA and Together AI, is used to produce new elements.

  24. Introduction to game development for the Web

    If you want your users to be able to use gamepads or other game controllers to work your game, you'll need this API. HTML and CSS. Together, these two technologies let you build, style, and lay out your game's user interface. Part of HTML is the <canvas> element, which provides one way to do 2D graphics. HTML audio.

  25. Introduction to HTML

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.