How to create a tetris game using Canvas?

Oct 22, 2025

Leave a message

Ryan Liu
Ryan Liu
Customer Service Representative at Shandong Shengrun Textile Co.,LTD. I work closely with clients to ensure their needs are met and satisfied. Looking forward to sharing stories about our customer-centric approach.

Creating a Tetris game using Canvas is an exciting and rewarding project that combines programming skills with creativity. As a Canvas supplier, I've seen firsthand the versatility and potential of Canvas in various applications, including game development. In this blog post, I'll guide you through the process of creating a simple Tetris game using HTML5 Canvas, sharing insights and tips along the way.

Understanding the Basics of Canvas

Before diving into the Tetris game development, it's essential to have a basic understanding of HTML5 Canvas. Canvas is an HTML element that provides a fixed-size drawing surface on which you can use JavaScript to draw graphics, animations, and more. It offers a wide range of drawing functions, such as drawing lines, rectangles, arcs, and filling shapes with colors.

Polyester Water Proof Canvas Fabric For Tent With UVPolyester Water Proof Canvas Fabric For Tent With UV

To get started, create a new HTML file and add a Canvas element to it:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tetris Game</title>
</head>

<body>
    <canvas id="gameCanvas" width="300" height="600"></canvas>
    <script src="script.js"></script>
</body>

</html>

In this example, we've created a Canvas element with an ID of "gameCanvas" and set its width to 300 pixels and height to 600 pixels. We've also linked an external JavaScript file named "script.js" where we'll write our game logic.

Setting Up the Game Environment

Now that we have our Canvas element in place, let's set up the game environment in our JavaScript file. First, we need to get a reference to the Canvas element and its 2D drawing context:

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

The getContext('2d') method returns an object that provides a set of methods and properties for drawing on the Canvas. We'll use this context to draw the Tetris blocks and the game board.

Defining the Tetrominoes

Tetrominoes are the geometric shapes that fall from the top of the Tetris game board. There are seven different types of Tetrominoes, each consisting of four squares arranged in a specific shape. We can represent each Tetromino as a 2D array of numbers, where 1 represents a filled square and 0 represents an empty square.

const SHAPES = [
    [
        [1, 1, 1, 1]
    ],
    [
        [1, 1],
        [1, 1]
    ],
    [
        [1, 1, 0],
        [0, 1, 1]
    ],
    [
        [0, 1, 1],
        [1, 1, 0]
    ],
    [
        [1, 1, 1],
        [0, 1, 0]
    ],
    [
        [1, 1, 1],
        [1, 0, 0]
    ],
    [
        [1, 1, 1],
        [0, 0, 1]
    ]
];

const COLORS = [
    'cyan', 'yellow', 'orange', 'blue', 'green', 'purple', 'red'
];

In this code, we've defined an array of shapes and an array of colors. Each shape corresponds to a different Tetromino, and each color corresponds to the color of the Tetromino.

Drawing the Tetrominoes

Now that we have our Tetrominoes defined, let's write a function to draw them on the Canvas. We'll create a function that takes a shape, a color, and the position of the shape on the game board as parameters.

function drawShape(shape, color, x, y) {
    shape.forEach((row, i) => {
        row.forEach((value, j) => {
            if (value === 1) {
                ctx.fillStyle = color;
                ctx.fillRect((x + j) * 30, (y + i) * 30, 30, 30);
                ctx.strokeStyle = 'black';
                ctx.strokeRect((x + j) * 30, (y + i) * 30, 30, 30);
            }
        });
    });
}

This function iterates over each square in the shape and checks if it's a filled square (value === 1). If it is, it fills the square with the specified color and adds a black border around it.

Generating Random Tetrominoes

In a Tetris game, the Tetrominoes fall from the top of the game board randomly. To implement this, we'll create a function that generates a random Tetromino and its corresponding color.

function getRandomShape() {
    const randomIndex = Math.floor(Math.random() * SHAPES.length);
    return {
        shape: SHAPES[randomIndex],
        color: COLORS[randomIndex]
    };
}

This function uses the Math.random() method to generate a random index between 0 and the length of the SHAPES array. It then returns an object containing the randomly selected shape and its corresponding color.

Implementing the Game Loop

The game loop is the heart of any game. It continuously updates the game state, draws the game elements on the Canvas, and checks for collisions. In our Tetris game, we'll use the requestAnimationFrame() method to create a smooth animation.

let currentShape = getRandomShape();
let currentX = 3;
let currentY = 0;

function gameLoop() {
    // Clear the Canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Draw the current shape
    drawShape(currentShape.shape, currentShape.color, currentX, currentY);

    // Move the shape down
    currentY++;

    // Request the next frame
    requestAnimationFrame(gameLoop);
}

gameLoop();

In this code, we've initialized the current shape and its position on the game board. The gameLoop() function clears the Canvas, draws the current shape, moves the shape down one step, and then requests the next frame using requestAnimationFrame().

Handling Collisions

One of the most important aspects of a Tetris game is handling collisions. When a Tetromino reaches the bottom of the game board or collides with another Tetromino, it should stop moving and a new Tetromino should be generated.

function isCollision(shape, x, y) {
    for (let i = 0; i < shape.length; i++) {
        for (let j = 0; j < shape[i].length; j++) {
            if (shape[i][j] === 1) {
                const newX = x + j;
                const newY = y + i;
                if (newX < 0 || newX >= 10 || newY >= 20) {
                    return true;
                }
                // Check for collision with other blocks (not implemented yet)
            }
        }
    }
    return false;
}

function gameLoop() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    if (!isCollision(currentShape.shape, currentX, currentY + 1)) {
        currentY++;
    } else {
        // Place the shape on the board and generate a new one
        currentShape = getRandomShape();
        currentX = 3;
        currentY = 0;
    }

    drawShape(currentShape.shape, currentShape.color, currentX, currentY);

    requestAnimationFrame(gameLoop);
}

In this updated code, we've added a isCollision() function that checks if the current shape will collide with the bottom of the game board or other blocks. If there's no collision, the shape moves down one step. Otherwise, the shape is placed on the board and a new shape is generated.

Adding User Input

To make the game more interactive, we need to add user input to control the movement of the Tetrominoes. We can use the addEventListener() method to listen for keyboard events and update the position of the current shape accordingly.

document.addEventListener('keydown', function (event) {
    if (event.key === 'ArrowLeft' &&!isCollision(currentShape.shape, currentX - 1, currentY)) {
        currentX--;
    } else if (event.key === 'ArrowRight' &&!isCollision(currentShape.shape, currentX + 1, currentY)) {
        currentX++;
    } else if (event.key === 'ArrowDown' &&!isCollision(currentShape.shape, currentX, currentY + 1)) {
        currentY++;
    }
});

In this code, we're listening for the left, right, and down arrow keys. When a key is pressed, we check if the current shape can move in the specified direction without colliding with anything. If it can, we update the position of the shape.

Conclusion

In this blog post, we've learned how to create a simple Tetris game using HTML5 Canvas. We've covered the basics of Canvas, defined the Tetrominoes, implemented the game loop, handled collisions, and added user input. This is just a starting point, and there are many ways to improve the game, such as adding rotation to the Tetrominoes, clearing full lines, and keeping score.

As a Canvas supplier, we offer a wide range of high-quality Canvas products suitable for various applications. If you're interested in using Canvas for your projects, check out our Polyester Water Proof Canvas Fabric For Tent With UV, 100% Cotton Dyed Fabric 20x20, 60x60 Width 44/45, and Waterproof Dyed Fabric.

If you have any questions or would like to discuss your specific requirements, feel free to reach out to us for a detailed consultation and procurement discussion.

References

  • Mozilla Developer Network: HTML5 Canvas API
  • Game Programming Patterns by Robert Nystrom
Send Inquiry
you dream it, we design it
Shandong Shengrun Textile Co.,LTD.
contact us