To draw a simple shape, you need to set the canvas element and get the 2D context first. 1. Add the

Drawing a simple shape on an HTML5 canvas is straightforward once you set up the canvas element and get its drawing context. Here's how you can do it step by step.

1. Set up the <canvas></canvas>
element
First, add a <canvas></canvas>
tag in your HTML. Give it an id
so you can easily reference it in JavaScript, and set its width
and height
attributes:
<canvas id="myCanvas" width="200" height="200"></canvas>
? Note: Use the width
and height
attributes directly on the canvas, not CSS, to avoid distortion.

2. Get the 2D drawing context
In JavaScript, get the canvas element and its 2D rendering context:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
The ctx
object is what you'll use to draw shapes, lines, and colors.

3. Draw a simple rectangle
Let's draw a solid red rectangle:
ctx.fillStyle = 'red'; // Set fill color
ctx.fillRect(10, 10, 150, 100); // (x, y, width, height)
This draws a 150×100 pixel red rectangle starting at coordinates (10, 10) from the top-left corner of the canvas.
Full example
Here's a complete working example:
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(20, 20, 100, 50);
</script>
This draws a blue rectangle.
Other basic shapes
Stroke (outline) rectangle :
ctx.strokeStyle = 'green';
ctx.strokeRect(10, 10, 100, 50);
Clear a rectangle :
ctx.clearRect(0, 0, canvas.width, canvas.height); // Useful for animations
Custom path (like a triangle) :
ctx.beginPath();
ctx.moveTo(50, 10); // Start point
ctx.lineTo(100, 100); // Line to bottom-right
ctx.lineTo(0, 100); // Line to bottom-left
ctx.closePath(); // Back to start
ctx.fillStyle = 'purple';
ctx.fill();
Basically, you just need a canvas, a context, and a few method calls. The key is starting with getContext('2d')
and then using drawing methods like fillRect
, strokeRect
, or path commands.
The above is the detailed content of How do you draw a simple shape on an HTML5 canvas?. For more information, please follow other related articles on the PHP Chinese website!