Canvas API
Drawing 2D graphics in the browser — shapes, text, images, animations, and pixel manipulation with the HTML5 Canvas.
What it is, in plain English: The Canvas API provides a 2D drawing surface in the browser via the
Drawing on the web
The Canvas API gives you a blank drawing surface in the browser. Unlike HTML elements, canvas has no DOM nodes for each shape — you issue drawing commands and pixels appear. This makes it much faster for things that change constantly, like animations and games.
Setup
<!-- HTML: -->
<canvas id="myCanvas" width="400" height="300"></canvas>
// JavaScript:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d"); // 2D rendering context
// Canvas coordinate system:
// (0, 0) is top-left
// x increases to the right
// y increases downwardShapes
// Filled rectangle: x, y, width, height
ctx.fillStyle = "royalblue";
ctx.fillRect(10, 10, 100, 50);
// Stroked (outlined) rectangle:
ctx.strokeStyle = "coral";
ctx.lineWidth = 2;
ctx.strokeRect(130, 10, 100, 50);
// Clear a rectangle (erases to transparent):
ctx.clearRect(50, 25, 20, 20);
// Circle using arc():
ctx.fillStyle = "gold";
ctx.beginPath();
ctx.arc(
250, 35, // center x, y
25, // radius
0, // start angle (radians)
Math.PI * 2 // end angle (full circle = 2π)
);
ctx.fill(); // or ctx.stroke() for outlinedPaths — for complex shapes
// Always beginPath() before drawing, then fill() or stroke():
ctx.fillStyle = "mediumseagreen";
ctx.beginPath();
ctx.moveTo(100, 100); // starting point
ctx.lineTo(200, 100); // line to...
ctx.lineTo(150, 180); // line to...
ctx.closePath(); // line back to start
ctx.fill(); // fill the shape
// Curves:
ctx.strokeStyle = "purple";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(20, 200);
ctx.bezierCurveTo(80, 130, 160, 270, 220, 200); // cp1x, cp1y, cp2x, cp2y, endX, endY
ctx.stroke();Text and images
// Text:
ctx.fillStyle = "#333";
ctx.font = "bold 24px Arial";
ctx.textAlign = "center"; // "left", "center", "right"
ctx.textBaseline = "middle"; // "top", "middle", "bottom"
ctx.fillText("Hello Canvas!", canvas.width / 2, canvas.height / 2);
// Measure text width (for layout):
const metrics = ctx.measureText("Hello Canvas!");
console.log("Text width:", metrics.width);
// Image:
const img = new Image();
img.onload = () => {
ctx.drawImage(img, 10, 10); // draw at (10,10)
ctx.drawImage(img, 10, 10, 100, 80); // draw and resize to 100x80
};
Try It Yourself
Official Sources
- MDN Web Docs — Canvas API
- MDN Web Docs — Canvas tutorial
- MDN Web Docs — OffscreenCanvas
- MDN Web Docs — WebGL API
The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.