Explore the fundamentals of drawing with the HTML5 Canvas and JavaScript. Learn how to create shapes, lines, and complex graphics with practical code examples.
The HTML5 Canvas is a powerful element that allows you to draw graphics directly on a web page using JavaScript. Whether you’re creating simple shapes or complex animations, understanding the basics of canvas drawing is essential for any budding coder. In this section, we’ll explore how to set up the canvas, draw basic shapes, and use colors and styles to bring your drawings to life.
Before you can start drawing, you need to access the canvas element in your HTML and get its drawing context. The context is what you’ll use to draw shapes, lines, and other graphics.
Here’s a simple example of how to access the canvas and its 2D drawing context:
<canvas id="myCanvas" width="400" height="200"></canvas>
let canvas = document.getElementById('myCanvas');
let ctx = canvas.getContext('2d');
In this example, we first select the canvas element by its ID using document.getElementById
. Then, we call getContext('2d')
to get the 2D drawing context, which provides the methods needed for drawing.
Rectangles are one of the simplest shapes you can draw on the canvas. You can fill them with color or just draw their outlines.
To draw a filled rectangle, use the fillRect
method:
ctx.fillStyle = '#FF0000'; // Set fill color to red
ctx.fillRect(10, 10, 100, 50); // Draw rectangle at (10, 10) with width 100 and height 50
This code sets the fill color to red using fillStyle
and then draws a rectangle starting at coordinates (10, 10) with a width of 100 pixels and a height of 50 pixels.
Lines are drawn using a sequence of commands to define the path and then stroking it.
Here’s how to draw a simple line:
ctx.beginPath(); // Start a new path
ctx.moveTo(20, 20); // Move the pen to (20, 20)
ctx.lineTo(200, 20); // Draw a line to (200, 20)
ctx.stroke(); // Render the path
In this example, beginPath
starts a new path, moveTo
sets the starting point, lineTo
defines the end point, and stroke
draws the line on the canvas.
Circles and arcs are drawn using the arc
method, which requires a center point, radius, and start and end angles.
Here’s how to draw a filled circle:
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI); // Center at (100, 75), radius 50
ctx.fill(); // Fill the circle
The arc
method takes five parameters: the x and y coordinates of the center, the radius, the start angle, and the end angle. Here, 0
to 2 * Math.PI
draws a full circle.
The canvas API provides several properties to style your drawings, such as fillStyle
for fill color and strokeStyle
for line color.
The fillStyle
property sets the color used to fill shapes. It can be a color name, hex value, or even a gradient.
ctx.fillStyle = 'blue';
ctx.fillRect(120, 10, 100, 50);
The strokeStyle
property sets the color for lines and outlines.
ctx.strokeStyle = 'green';
ctx.lineWidth = 5; // Set line width
ctx.strokeRect(120, 80, 100, 50); // Draw rectangle outline
Once you’re comfortable with basic shapes, you can explore more advanced techniques like gradients, patterns, and image drawing.
Gradients create smooth transitions between colors. You can create linear or radial gradients.
let gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'yellow');
ctx.fillStyle = gradient;
ctx.fillRect(10, 150, 200, 50);
Patterns use images to fill shapes. First, load an image and then use it to create a pattern.
let img = new Image();
img.src = 'pattern.png';
img.onload = function() {
let pattern = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(220, 10, 100, 100);
};
You can also draw images and text on the canvas.
To draw an image, use the drawImage
method. You can specify the position and size.
let img = new Image();
img.src = 'image.png';
img.onload = function() {
ctx.drawImage(img, 10, 220, 100, 100);
};
Use the fillText
or strokeText
methods to draw text.
ctx.font = '20px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas!', 10, 350);
save()
and restore()
to manage the drawing state when making complex drawings.ctx.clearRect(x, y, width, height)
to clear parts of the canvas.beginPath()
when starting a new shape to avoid unexpected results.The HTML5 Canvas API is a versatile tool for creating graphics with JavaScript. By mastering the basics of drawing shapes, lines, and using colors, you can create stunning visuals and interactive experiences. As you become more comfortable, explore advanced techniques like animations and real-time graphics to expand your skills.