Question
Answer and Explanation
Drawing a Pac-Man ghost in JavaScript typically involves using the HTML5 Canvas element. Here's a breakdown of how you can achieve this:
1. Set up the HTML Canvas:
- First, you need an HTML canvas element where you'll draw the ghost. Add this to your HTML:
<canvas id="ghostCanvas" width="200" height="200"></canvas>
2. Get the Canvas Context:
- In your JavaScript, get the canvas element and its 2D rendering context:
const canvas = document.getElementById('ghostCanvas');
const ctx = canvas.getContext('2d');
3. Draw the Ghost Body:
- The ghost's body is essentially a rounded rectangle with a wavy bottom. You can achieve this using arcs and lines:
ctx.beginPath();
ctx.arc(100, 70, 50, 0, Math.PI, true); // Top semicircle
ctx.lineTo(50, 120); // Left side
ctx.quadraticCurveTo(60, 130, 70, 120); // First wave
ctx.quadraticCurveTo(80, 130, 90, 120); // Second wave
ctx.quadraticCurveTo(100, 130, 110, 120); // Third wave
ctx.quadraticCurveTo(120, 130, 130, 120); // Fourth wave
ctx.lineTo(150, 120); // Right side
ctx.closePath();
ctx.fillStyle = 'red'; // Ghost color
ctx.fill();
4. Draw the Eyes:
- Add two circles for the eyes:
ctx.beginPath();
ctx.arc(80, 60, 10, 0, 2 Math.PI); // Left eye
ctx.arc(120, 60, 10, 0, 2 Math.PI); // Right eye
ctx.fillStyle = 'white';
ctx.fill();
ctx.beginPath();
ctx.arc(80, 60, 5, 0, 2 Math.PI); // Left pupil
ctx.arc(120, 60, 5, 0, 2 Math.PI); // Right pupil
ctx.fillStyle = 'black';
ctx.fill();
5. Complete JavaScript Code:
document.addEventListener('DOMContentLoaded', function() {
const canvas = document.getElementById('ghostCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 70, 50, 0, Math.PI, true);
ctx.lineTo(50, 120);
ctx.quadraticCurveTo(60, 130, 70, 120);
ctx.quadraticCurveTo(80, 130, 90, 120);
ctx.quadraticCurveTo(100, 130, 110, 120);
ctx.quadraticCurveTo(120, 130, 130, 120);
ctx.lineTo(150, 120);
ctx.closePath();
ctx.fillStyle = 'red';
ctx.fill();
ctx.beginPath();
ctx.arc(80, 60, 10, 0, 2 Math.PI);
ctx.arc(120, 60, 10, 0, 2 Math.PI);
ctx.fillStyle = 'white';
ctx.fill();
ctx.beginPath();
ctx.arc(80, 60, 5, 0, 2 Math.PI);
ctx.arc(120, 60, 5, 0, 2 Math.PI);
ctx.fillStyle = 'black';
ctx.fill();
});
This code will draw a basic Pac-Man ghost on your canvas. You can adjust the coordinates, colors, and sizes to customize the appearance further. Remember to include this JavaScript code in a <script>
tag in your HTML or in an external JavaScript file.