Introduction to the HTML5 Canvas

Introduction to the HTML5 Canvas

One of the most exciting features of the HTML5 standard is the canvas tag. The canvas allows arbitrary 2D rendering of shapes and images as well as interactions via standard events. This can be used for interactive presentations, graphs, dashboards, simulations and, of course, games. The canvas has an API that is pretty low-level and includes various functions.

In this article, I’ll demonstrate some of the capabilities of the HTML5 canvas and integration with other HTML elements by implementing Conway’s game of life. This is a visualization of a very entertaining cellular automata that can generate very surprising patterns from super-simple ground rules. You can find the full source code here.

This is what it looks like:

If you click the button while it’s running the simulation stops and you can toggle individual cells by clicking them and then continue running by clicking the button again.

Setup

First, we need a basic HTML page to host our canvas:

Your browser does not support the HTML 5 Canvas element.

There is also a button there to alternate between two modes: Run mode — where the simulation is running and Edit mode — where you can edit the field.

In the beginning of the script tag we get the various objects from the DOM with which we will interact — the canvas itself, the graphics context and of course the button:

canvas = document.getElementById("main_canvas");context = canvas.getContext("2d");button = document.getElementById("button");

Then the canvas is properly sized and a few variables that will determine the look and feel are initialized:

canvas_size = 1000;canvas.width = canvas_size;canvas.height = canvas_size;size = 100;square = 10;running = false; 

The ‘running’ variable controls the mode. When, it’s ‘false’ we’re in editing mode

Finally, we get the board, which is a 2d array 1000×1000 initialized to zeros

board = get_board();function get_board() {    // Create 2d array    board = new Array(size);    for (var i = 0; i < size; ++i) {        board[i] = new Array(size);        for (var j = 0; j < size; ++j) {            board[i][j] = 0;        }    }    return board;} 

The window.onload() Function

In the browser, the primary place to hook up your JavaScript is the window.onload() callback function. The browser uses this function when the page has finished loading and all the HTML elements are accessible through the DOM.

window.onload = function() {    canvas.addEventListener("mousedown", onMouseDown, false);    main();    setInterval("main()", 30);};

Here, the onload() function is very simple. It sets up the onMouseDown() function to respond to mouse down events, then calls the main() function and sets a timer to repeatedly call it every 30 milliseconds, which is about 33 frames per second.

Main Loop

The main loop's logic is simple too. Clear the canvas, draw the current state of the board by displaying a rectangle with the right color in each cell position. Finally, if we're in the "running" state update the board by calling the update() function that does the heavy lifting and returns an updated board.

function main() {    context.clearRect ( 0 , 0 , canvas.width , canvas.height );    for (var i = 0; i < size; ++i) {        for (var j = 0; j < size; ++j) {            context.fillStyle = board[i][j] == 1 ? "black" : "magenta";            context.fillRect(i * square, j * square, square - 1, square - 1);        }    }    if (running)        board = update();}

Updating State

The update function implements the rules of Conway's game of life. Every live cell stays alive if, and only if, it has 2 or 3 live neighbors. Every dead cell comes alive if, and only if, it has exactly 3 live neighbors. First a new board is created and then the state of each cell is determined by counting its neighbors using the get_neighbors() function

function update() {    var new_board = new Array(size);    for (var i = 0; i < size; ++i) {        new_board[i] = new Array(size);        for (var j = 0; j < size; ++j) {            var value = board[i][j];            new_board[i][j] = value;            var neighbors = get_neighbors(i, j);            if (value == 1) {                if (neighbors < 2 || neighbors > 3)                    new_board[i][j] = 0;            } else {                if (neighbors == 3)                    new_board[i][j] = 1;            }        }    }    return new_board;}

The get_neighbors() function checks all the neighbors around a cell. Note, that cells on the edge have fewer neighbors and this is taken into account.

function get_neighbors(x, y) {    var count = 0;    for (var i = -1; i < 2; ++i) {        for (var j = -1; j < 2; ++j) {            var nx = x + i;            var ny = y + j;            if (i == 0 && j == 0)                continue;            if (nx < 0 || nx >= size)                continue;            if (ny < 0 || ny >= size)                continue;            count += board[nx][ny];        }    }    return count;}

Interaction

There are two types of interaction that are very typical: clicking on a user interface element such as a button and clicking on the canvas itself and causing some effect. The button is used to switch the program's mode between "Running" and "Editing". Here is the code that just toggles the "running" variable and changes the text of the button:

function onButtonClick() {   running = ~running;   button.innerText = button.innerText == 'Run' ? 'Stop' : 'Run';}

When you are in editing mode and you click with the mouse on a cell, it toggles the cell  — a live cell becomes dead and a dead cell becomes live:

function onMouseDown(e) {    if (running)        return;    var x = Math.floor(e.offsetX / square);    var y = Math.floor(e.offsetY / square);    toggle(x, y);}function toggle(x, y) {    board[x][y] = 1 - board[x][y];}

Conclusion

The HTML 5 Canvas is a versatile new element that provides the power to create stunning interactive visualizations in a cross-browser manner. It can add a lot to the user experience when used properly. Developers can get a handle on it quickly, as it uses the familiar web platform of HTML/CSS/JavaScript.

devx-admin

devx-admin

Share the Post:
2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications,

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure.

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company.

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists

AI Tool

Unleashing AI Power with Microsoft 365 Copilot

Microsoft has recently unveiled the initial list of Australian clients who will benefit from Microsoft 365 (M365) Copilot through the exclusive invitation-only global Early Access Program. Prominent organizations participating in

Microsoft Egnyte Collaboration

Microsoft and Egnyte Collaboration

Microsoft has revealed a collaboration with Egnyte, a prominent platform for content cooperation and governance, with the goal of improving real-time collaboration features within Microsoft 365 and Microsoft Teams. This

Best Laptops

Top Programming Laptops of 2023

In 2023, many developers prioritize finding the best laptop for programming, whether at home, in the workplace, or on the go. A high-performing, portable, and user-friendly laptop could significantly influence

Renaissance Gaming Magic

AI Unleashes A Gaming Renaissance

In recent times, artificial intelligence has achieved remarkable progress, with resources like ChatGPT becoming more sophisticated and readily available. Pietro Schirano, the design lead at Brex, has explored the capabilities

New Apple Watch

The New Apple Watch Ultra 2 is Awesome

Apple is making waves in the smartwatch market with the introduction of the highly anticipated Apple Watch Ultra 2. This revolutionary device promises exceptional performance, robust design, and a myriad

Truth Unveiling

Unveiling Truths in Bowen’s SMR Controversy

Tony Wood from the Grattan Institute has voiced his concerns over Climate and Energy Minister Chris Bowen’s critique of the Coalition’s support for small modular nuclear reactors (SMRs). Wood points

Avoiding Crisis

Racing to Defy Looming Financial Crisis

Chinese property developer Country Garden is facing a liquidity challenge as it approaches a deadline to pay $15 million in interest associated with an offshore bond. With a 30-day grace

Open-Source Development

Open-Source Software Development is King

The increasingly digital world has led to the emergence of open-source software as a critical factor in modern software development, with more than 70% of the infrastructure, products, and services

Home Savings

Sensational Savings on Smart Home Security

For a limited time only, Amazon is offering massive discounts on a variety of intelligent home devices, including products from its Ring security range. Running until October 2 or while

Apple Unleashed

A Deep Dive into the iPhone 15 Pro Max

Apple recently unveiled its groundbreaking iPhone 15 Pro and iPhone 15 Pro Max models, featuring a revolutionary design, extraordinary display technology, and unrivaled performance. These new models are the first

Renewable Crypto Miners

Crypto Miners Embrace Renewable Energy?

As the cryptocurrency sector deals with the fallout from the FTX and Celsius exchange collapses, Bitcoin miners are increasingly exploring alternative energy sources to reduce expenses and maintain profitability. Specialists

Laptop Savings

The HP Omen 16 is a Gamer’s Dream

Best Buy is currently offering an unbeatable deal on the HP Omen 16 gaming laptop, giving potential buyers the chance to save a significant $720 on their purchase. Originally priced

How to Check for Vulnerabilities in Exchange Server

It is imperative to keep your systems and infrastructure up-to-date to mitigate security issues and loopholes, and to protect them against any known vulnerabilities and security risks. There are many

Data Center Creation

Transforming Corporate Campuses into Thriving Data Centers

Dallas-based developer Compass Datacenters has purchased a 197-acre ex-corporate campus in Hoffman Estates, Illinois for an estimated $194 million. This acquisition occurs as more companies are downsizing and consolidating their

Nano Unbeatable Value

Lenovo ThinkPad X1 Nano: Unbeatable Value

The Lenovo ThinkPad X1 Nano, a first-generation model beloved for its ergonomic keyboards and stylish appearance, is now available at an unbeatable price of $600 on eBay. Though this 13-inch

Assistant Revolution

Home Assistant Green Makes Your Home Futuristic

In recent times, the growing interest in smart home technology has led to the emergence of various devices and platforms that enable homeowners to control and manage their homes in

Ultimate Smart Home

Unlock Your Ultimate Smart Home Adventure

Ever thought about having a home where everything is tailored to your needs and runs smoothly? Home automation may significantly impact your daily life. Transform your space into an intelligent

Gaming Laptops

Lenovo Legion Laptops Revolutionize Gaming

The gaming laptop market has recently been graced with two potent contenders, the Lenovo Legion 9i and the Legion Pro 7i. Both laptops boast powerful 13th-gen Intel Core i9 processors

Fintech Revolution Leap

Figure’s Bold Leap Beyond Banking

Figure, a fast-growing fintech startup, recently retracted its bid to become a bank, sparking speculation that the process was too challenging. However, the true reason behind Figure’s decision was its