How to Draw a Pacman Ghost in JavaScript

Introduction

Drawing a Pacman ghost in JavaScript is not only a fun exercise but also a fantastic way to improve your skills in using the HTML Canvas API. The iconic ghost characters from the classic game are simple in design yet require an understanding of how to manipulate shapes, colors, and the canvas context in JavaScript. In this article, we will walk through the entire process of creating a colorful Pacman ghost using JavaScript.

Before we dive in, let’s take a moment to familiarize ourselves with what we’ll be building. The ghost will have a semi-circular top, a rectangular body, and eyes. The ghosts we’ll be creating can be adapted to feature the different colors of the iconic characters: Blinky (red), Pinky (pink), Inky (cyan), and Clyde (orange). This flexibility allows you to experiment and even create your custom designs!

By the end of this tutorial, you will have a better understanding of working with the canvas in JavaScript and how to program a drawing function that can be reused with different parameters. Let’s get started!

Setting Up Your HTML Canvas

First, we need to set up an HTML environment with a canvas element where we will draw our Pacman ghost. Create an HTML file and include the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Draw Pacman Ghost in JavaScript</title>
</head>
<body>
    <canvas id="pacmanGhostCanvas" width="400" height="400" style="border:1px solid #000;"></canvas>
    <script src="script.js"></script>
</body>
</html>

This code creates a simple webpage with a canvas element that is 400×400 pixels in size. It also links to an external JavaScript file called script.js, where we will write the drawing logic.

Your next step is to create the script.js file in the same directory as your HTML file. This is where we will write the JavaScript code to draw the Pacman ghost.

Creating the Drawing Function

Now that we have our canvas set up, let’s create the drawing function in script.js. Start by grabbing the canvas context, which is essential for drawing shapes and colors.

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

This code retrieves the canvas element and initializes the 2D drawing context, which allows us to draw graphics on the canvas.

Let’s create our main function to draw the Pacman ghost. We will use a series of canvas methods to render different parts of the ghost.

function drawPacmanGhost(color, x, y) {
    // Draw the body
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.arc(x, y, 50, Math.PI, 0, true); // Top half circle
    ctx.lineTo(x - 50, y + 100); // Bottom left
    ctx.lineTo(x + 50, y + 100); // Bottom right
    ctx.closePath();
    ctx.fill();

    // Draw the eyes
    ctx.fillStyle = 'white';
    ctx.beginPath();
    ctx.arc(x - 20, y - 10, 10, 0, Math.PI * 2, true); // Left eye
    ctx.arc(x + 20, y - 10, 10, 0, Math.PI * 2, true); // Right eye
    ctx.fill();

    // Draw the pupils
    ctx.fillStyle = 'black';
    ctx.beginPath();
    ctx.arc(x - 20, y - 10, 5, 0, Math.PI * 2, true); // Left pupil
    ctx.arc(x + 20, y - 10, 5, 0, Math.PI * 2, true); // Right pupil
    ctx.fill();
}

This drawPacmanGhost function takes three parameters: the color of the ghost, and the x and y coordinates for positioning. Inside this function, we first set the fill style color and draw the lower half of the ghost’s body using the arc method. Then, we create two white circles for the eyes, followed by two smaller black circles for the pupils.

Drawing Multiple Ghosts

Now that we have our drawing function set up, you might want to create multiple Pacman ghosts on the canvas. To do this, simply call the drawPacmanGhost function with different parameters. Update your JavaScript file like this:

drawPacmanGhost('red', 100, 100);
drawPacmanGhost('pink', 200, 100);
drawPacmanGhost('cyan', 300, 100);
drawPacmanGhost('orange', 400, 100);

With this code, each call to drawPacmanGhost will render a ghost of a different color at specified positions. You can experiment with the coordinates to arrange the ghosts as you like.

Once updated, your entire script.js code should look something like this:

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

function drawPacmanGhost(color, x, y) {
    // Draw the body
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.arc(x, y, 50, Math.PI, 0, true);
    ctx.lineTo(x - 50, y + 100);
    ctx.lineTo(x + 50, y + 100);
    ctx.closePath();
    ctx.fill();

    // Draw the eyes
    ctx.fillStyle = 'white';
    ctx.beginPath();
    ctx.arc(x - 20, y - 10, 10, 0, Math.PI * 2, true);
    ctx.arc(x + 20, y - 10, 10, 0, Math.PI * 2, true);
    ctx.fill();

    // Draw the pupils
    ctx.fillStyle = 'black';
    ctx.beginPath();
    ctx.arc(x - 20, y - 10, 5, 0, Math.PI * 2, true);
    ctx.arc(x + 20, y - 10, 5, 0, Math.PI * 2, true);
    ctx.fill();
}

drawPacmanGhost('red', 100, 100);
drawPacmanGhost('pink', 200, 100);
drawPacmanGhost('cyan', 300, 100);
drawPacmanGhost('orange', 400, 100);

Reloading the HTML page in your browser will now show four colorful Pacman ghosts, each drawn using our JavaScript function.

Enhancing the Ghosts with Animation

To take our drawing a step further, let’s add some simple animations to our Pacman ghosts. By changing their position over time, we can create the illusion of movement across the canvas. We can achieve this by using the requestAnimationFrame method, which is great for animations in the browser.

Here’s how you can enhance your existing code to animate the ghosts:

let offsetX = 0;

function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
    drawPacmanGhost('red', 100 + offsetX, 100);
    drawPacmanGhost('pink', 200 + offsetX, 100);
    drawPacmanGhost('cyan', 300 + offsetX, 100);
    drawPacmanGhost('orange', 400 + offsetX, 100);

    offsetX += 1; // Move ghosts to the right
    if (offsetX > canvas.width) offsetX = 0; // Reset when out of frame

    requestAnimationFrame(animate);
}

animate();

In this code, we create an animate function that first clears the previous drawings from the canvas and then redraws the ghosts at new x positions based on offsetX. This value increases over time, giving the illusion that the ghosts are moving across the screen.

Finally, we call requestAnimationFrame inside the animate function, which requests the browser to execute the next frame of the animation. This will create a smooth animation for our Pacman ghosts.

Conclusion

Congratulations! You now have a fully functional Pacman ghost drawing application in JavaScript. You’ve learned how to set up the canvas, draw shapes, and even animate your ghosts. This project not only showcases your skills in JavaScript and canvas manipulation but also serves as a great foundation for exploring more complex graphics programming.

There are endless possibilities for enhancement. Try adding more features, such as user controls to change ghost colors dynamically or even create ghost movement patterns to mimic those of the classic game. You could also experiment with different ghost designs or animations, such as blinking eyes or bouncing movements.

By diving into projects like this, you’re honing your JavaScript skills while having fun. Don’t forget to explore other creative ventures using the canvas or even delve into libraries like p5.js to unleash your artistic coding potential. Happy coding!

Scroll to Top