
Browser Canvas API Cheatsheet
šØ Browser Canvas API Cheatsheet
The Canvas API lets you draw graphics with JavaScript. This cheatsheet covers shapes, text, images, transformations, and pixel manipulation.
ā Getting started ā Drawing shapes ā Paths and lines ā Text and images ā Transformations ā Pixel manipulation
#javascript #browser #canvas #graphics #animation #webdev #frontend #coding #tips
The Canvas API provides a 2D drawing surface controlled entirely with JavaScript. It's used for charts, games, image editing, and visualizations.
This cheatsheet provides a quick reference to the Canvas 2D API.
Getting started
Get the 2D rendering context from a <canvas> element.
<canvas id="canvas" width="400" height="300"></canvas>const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");The coordinate system starts at the top-left corner: x goes right, y goes down.
Drawing shapes
Rectangles are the only built-in shape.
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 100, 80); // filled rectangle
ctx.strokeStyle = "red";
ctx.lineWidth = 2;
ctx.strokeRect(10, 10, 100, 80); // outlined rectangle
ctx.clearRect(0, 0, canvas.width, canvas.height); // erase an areaPaths and lines
Build custom shapes with paths.
ctx.beginPath();
ctx.moveTo(50, 50); // start point
ctx.lineTo(150, 50); // line to
ctx.lineTo(100, 120);
ctx.closePath(); // back to start
ctx.fillStyle = "green";
ctx.fill(); // or ctx.stroke()Circles and curves.
// arc(x, y, radius, startAngle, endAngle)
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2); // full circle
ctx.fill();
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI); // half circle
ctx.stroke();
// Quadratic and bezier curves
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.quadraticCurveTo(50, 100, 100, 0);
ctx.bezierCurveTo(120, -50, 180, 150, 200, 0);
ctx.stroke();Line styling.
ctx.lineWidth = 4;
ctx.lineCap = "round"; // "butt", "round", "square"
ctx.lineJoin = "bevel"; // "miter", "round", "bevel"
ctx.setLineDash([10, 5]); // dashed lineColors and gradients
Fill and stroke accept colors, gradients, and patterns.
ctx.fillStyle = "#3b82f6";
ctx.fillStyle = "rgb(59, 130, 246)";
ctx.fillStyle = "rgba(59, 130, 246, 0.5)";
// Linear gradient
const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, "blue");
gradient.addColorStop(1, "purple");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 100);
// Radial gradient
const radial = ctx.createRadialGradient(100, 100, 10, 100, 100, 80);
radial.addColorStop(0, "white");
radial.addColorStop(1, "black");
ctx.fillStyle = radial;
ctx.fillRect(0, 0, 200, 200);Text
Draw and style text.
ctx.font = "bold 24px sans-serif";
ctx.fillStyle = "black";
ctx.textAlign = "center"; // "left", "center", "right"
ctx.textBaseline = "middle"; // "top", "middle", "bottom"
ctx.fillText("Hello", 200, 50); // filled text
ctx.strokeText("Hello", 200, 100); // outlined text
const metrics = ctx.measureText("Hello");
metrics.width; // text width in pixelsImages
Draw images, videos, or other canvases.
const img = new Image();
img.src = "photo.jpg";
img.onload = () => {
ctx.drawImage(img, 0, 0); // original size
ctx.drawImage(img, 0, 0, 200, 150); // scaled
// drawImage(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
ctx.drawImage(img, 50, 50, 100, 100, 0, 0, 200, 200); // crop and draw
};Transformations
Transform the coordinate system. Always save and restore state.
ctx.save(); // save current state
ctx.translate(100, 100); // move origin
ctx.rotate(Math.PI / 4); // rotate 45 degrees
ctx.scale(2, 2); // scale x2
ctx.fillRect(-25, -25, 50, 50); // drawn around new origin
ctx.restore(); // back to saved statePixel manipulation
Read and write raw pixel data.
// Read pixels
const imageData = ctx.getImageData(0, 0, 100, 100);
const pixels = imageData.data; // [r, g, b, a, r, g, b, a, ...]
// Invert colors
for (let i = 0; i < pixels.length; i += 4) {
pixels[i] = 255 - pixels[i]; // red
pixels[i + 1] = 255 - pixels[i + 1]; // green
pixels[i + 2] = 255 - pixels[i + 2]; // blue
}
ctx.putImageData(imageData, 0, 0);Exporting
Convert the canvas to an image.
canvas.toDataURL("image/png"); // data URL string
canvas.toDataURL("image/jpeg", 0.8); // with quality
// As a blob (better for large images)
canvas.toBlob((blob) => {
const url = URL.createObjectURL(blob);
}, "image/png");Animation loop
Redraw every frame with requestAnimationFrame.
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // clear frame
ctx.beginPath();
ctx.arc(x, 150, 20, 0, Math.PI * 2);
ctx.fill();
x = (x + 2) % canvas.width;
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);Best practices
ā
Clear the canvas each frame with clearRect before redrawing.
ā
Wrap transformations in save()/restore() to avoid state leaks.
ā
Use toBlob instead of toDataURL for large images.
ā Don't scale canvas via CSS. Set width/height attributes to avoid blurriness.
Full-Stack AI Developer Roadmap
From HTML & CSS to working with AI models, all in one structured roadmap.