Certainly! The HTML5 Canvas API provides a comprehensive set of functions for drawing various shapes, lines, text, and more on a canvas element. Below is a categorized list of commonly used Canvas API functions for drawing lines, rectangles, circles, text, and other shapes, along with brief descriptions.
1. Setting Up the Canvas Context
Before drawing, you need to obtain the drawing context from the canvas element:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d'); // 2D rendering context
2. Drawing Paths and Shapes
a. Basic Path Operations
-
beginPath()
- Starts a new path by emptying the list of sub-paths. Use this method when you want to create a new shape.
ctx.beginPath();
-
closePath()
- Connects the current point to the starting point of the current sub-path, creating a closed shape.
ctx.closePath();
-
moveTo(x, y)
- Moves the starting point of a new sub-path to the (x, y) coordinates.
ctx.moveTo(50, 50);
-
lineTo(x, y)
- Adds a straight line to the current sub-path from the current point to the (x, y) coordinates.
ctx.lineTo(150, 50);
b. Drawing Lines and Polygons
-
stroke()
- Strokes the current path with the current stroke style.
ctx.stroke();
-
fill()
- Fills the current path with the current fill style.
ctx.fill();
c. Drawing Rectangles
-
rect(x, y, width, height)
- Adds a rectangle to the current path.
ctx.rect(20, 20, 100, 50);
-
fillRect(x, y, width, height)
- Draws a filled rectangle directly without needing to call
beginPath() or fill().
ctx.fillRect(20, 20, 100, 50);
-
strokeRect(x, y, width, height)
- Draws the outline of a rectangle.
ctx.strokeRect(20, 20, 100, 50);
-
clearRect(x, y, width, height)
- Clears the specified rectangular area, making it fully transparent.
ctx.clearRect(20, 20, 100, 50);
d. Drawing Circles and Arcs
-
arc(x, y, radius, startAngle, endAngle, anticlockwise)
- Creates an arc/curve (used to create circles or partial circles).
ctx.arc(100, 75, 50, 0, Math.PI * 2, true); // Full circle
-
arcTo(x1, y1, x2, y2, radius)
- Creates an arc between two tangential lines.
ctx.arcTo(100, 50, 200, 50, 75);
-
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise)
ctx.ellipse(100, 75, 50, 25, Math.PI / 4, 0, Math.PI * 2);
e. Drawing Curves
-
quadraticCurveTo(cp1x, cp1y, x, y)
- Creates a quadratic Bézier curve.
ctx.quadraticCurveTo(150, 25, 200, 75);
-
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
- Creates a cubic Bézier curve.
ctx.bezierCurveTo(150, 25, 250, 125, 200, 75);
3. Drawing Text
-
fillText(text, x, y, maxWidth)
- Draws filled text at the specified position.
ctx.fillText('Hello Canvas', 50, 100);
-
strokeText(text, x, y, maxWidth)
- Draws text outlines at the specified position.
ctx.strokeText('Hello Canvas', 50, 100);
-
Text Styling Properties
-
ctx.font: Sets the current text style (e.g., size, family).
ctx.font = '16px Arial';
-
ctx.textAlign: Sets the current text alignment (left, right, center, start, end).
ctx.textAlign = 'center';
-
ctx.textBaseline: Sets the current text baseline (top, hanging, middle, alphabetic, ideographic, bottom).
ctx.textBaseline = 'middle';
4. Styling and Transformations
a. Stroke and Fill Styles
b. Transformations
-
translate(x, y)
- Moves the canvas and its origin to a different position.
ctx.translate(50, 50);
-
rotate(angle)
- Rotates the canvas by the specified angle (in radians).
ctx.rotate(Math.PI / 4); // 45 degrees
-
scale(scaleX, scaleY)
- Scales the canvas by the specified factors.
ctx.scale(2, 2); // Doubles the size
-
transform(a, b, c, d, e, f)
- Applies a matrix transformation.
ctx.transform(1, 0, 0, 1, 50, 50);
-
setTransform(a, b, c, d, e, f)
- Resets the current transformation to the identity matrix and applies the new transformation.
ctx.setTransform(1, 0, 0, 1, 0, 0); // Reset to default
-
save() and restore()
- Saves and restores the current drawing state (including transformations and styles).
ctx.save();
// ... apply transformations or styles
ctx.restore(); // Revert to saved state
5. Advanced Shapes and Patterns
a. Drawing Images
-
drawImage(image, dx, dy)
- Draws an image onto the canvas.
const img = new Image();
img.src = 'path/to/image.png';
img.onload = () => {
ctx.drawImage(img, 0, 0);
};
-
drawImage(image, dx, dy, dWidth, dHeight)
- Draws and scales the image.
ctx.drawImage(img, 0, 0, 100, 100);
-
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
- Draws a cropped region of the image.
ctx.drawImage(img, 50, 50, 100, 100, 0, 0, 100, 100);
b. Creating Patterns and Gradients
-
Patterns
-
createPattern(image, repetition)
- Creates a pattern using an image.
const pattern = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);
-
Gradients
-
createLinearGradient(x0, y0, x1, y1)
- Creates a linear gradient.
const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 100);
-
createRadialGradient(x0, y0, r0, x1, y1, r1)
- Creates a radial gradient.
const radialGradient = ctx.createRadialGradient(100, 100, 20, 100, 100, 100);
radialGradient.addColorStop(0, 'yellow');
radialGradient.addColorStop(1, 'green');
ctx.fillStyle = radialGradient;
ctx.fillRect(0, 0, 200, 200);
6. Clearing and Resetting
-
clearRect(x, y, width, height)
- Clears the specified rectangular area, making it fully transparent.
ctx.clearRect(0, 0, canvas.width, canvas.height);
7. Example: Drawing a Simple Scene
Here's a simple example that uses several of the functions listed above to draw a house with a roof, door, and sun:
// Draw the base of the house
ctx.fillStyle = '#8B4513'; // Brown color
ctx.fillRect(100, 150, 200, 150);
// Draw the roof
ctx.beginPath();
ctx.moveTo(100, 150);
ctx.lineTo(200, 50);
ctx.lineTo(300, 150);
ctx.closePath();
ctx.fillStyle = '#A52A2A'; // Roof color
ctx.fill();
// Draw the door
ctx.fillStyle = '#654321'; // Dark brown
ctx.fillRect(180, 220, 40, 80);
// Draw the sun
ctx.beginPath();
ctx.arc(400, 50, 30, 0, Math.PI * 2, false);
ctx.fillStyle = 'yellow';
ctx.fill();
ctx.stroke();
8. Additional Resources
-
MDN Web Docs - Canvas API: Comprehensive documentation and tutorials.
-
HTML Canvas Tutorials: Step-by-step guides for beginners.
-
Canvas Patterns and Gradients:
By leveraging these functions and properties, you can create a wide variety of graphics and interactive visualizations using the HTML5 Canvas API.