HTML5 Canvas API Reference: Methods and Properties for 2D Graphics
This comprehensive reference guide details the methods and properties of the HTML5 Canvas 2D rendering context, providing a complete resource for drawing shapes, lines, text, and images using JavaScript. Learn how to create dynamic graphics on your web pages!
HTML Canvas API Reference
This reference details the methods and properties of the HTML5 Canvas 2D rendering context, providing a comprehensive guide to drawing graphics using JavaScript.
Creating a Canvas
The <canvas>
element creates a rectangular area where you draw graphics using JavaScript. You must set the `width` and `height` attributes. A border can be added with CSS.
Creating a Canvas Element
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
The fallback text is displayed in browsers that don't support canvas.
Getting the 2D Rendering Context
To draw on the canvas, you need a 2D rendering context object. This is obtained using the `getContext("2d")` method.
Getting the 2D Context
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
The ctx
object now holds the tools for drawing.
Drawing Shapes and Lines
The Canvas API provides methods for drawing various shapes and lines. Here's a simple example using `fillRect()` to draw a filled rectangle:
Drawing a Filled Rectangle
ctx.fillStyle = "red"; // Set fill color
ctx.fillRect(10, 10, 100, 50); // Draw rectangle at (10,10), 100x50 pixels
Creating Paths
More complex shapes are drawn using paths. You begin a path with `beginPath()`, add points with `moveTo()` and `lineTo()`, and then render the path with `stroke()` or `fill()`.
Creating a Path
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 100);
ctx.lineTo(70, 100);
ctx.stroke(); // Draw the lines
Canvas API Reference
(The detailed reference for drawing methods, path methods, circle and curve methods, text methods, color/style/shadow methods, transformation methods, image drawing methods, ImageData object methods, compositing properties, and other methods would be added here, each with a brief description. Due to length constraints, this section is omitted, but it should follow a similar structure to the examples above using code snippets and "Try it Yourself" links where applicable.)
Browser Support
The Canvas element and API are widely supported in modern browsers.
(Browser support table would be added here.)
For a complete tutorial on the Canvas API, visit our Canvas Tutorial.