Grabbing a drawing surface from the DOM and preparing the 2 D context.
The <canvas>
element provides a bitmap surface that you draw on
using JavaScript. Everything rendered is immediate-mode; once a pixel is
drawn it becomes part of the bitmap until manually cleared or over-painted.
<canvas id="stage" width="640" height="360"></canvas>
<script>
const canvas = document.getElementById("stage");
const ctx = canvas.getContext("2d"); // default = 2D context
</script>
Context Type | Description / Use-case |
---|---|
"2d" | Pixel-based 2 D API (paths, text, images). |
"webgl" | Low-level GPU (OpenGL ES 2.0). |
"webgl2" | OpenGL ES 3.0 core features. |
"bitmaprenderer" | Blit ImageBitmap s efficiently. |
"webgpu" | Modern GPU API (spec draft). |
Understanding pixels, saves, and resets.
ctx.save();
ctx.translate(200, 150);
ctx.rotate(Math.PI / 4);
ctx.fillStyle = "crimson";
ctx.fillRect(-50, -50, 100, 100);
ctx.restore();
Rectangles, lines, arcs, Béziers, and custom shapes.
ctx.fillRect(x, y, w, h);
ctx.clearRect(x, y, w, h);
ctx.strokeRect(x, y, w, h);
ctx.beginPath();
ctx.moveTo(50, 60);
ctx.lineTo(150, 60);
ctx.lineTo(100, 140);
ctx.closePath();
ctx.fill(); // uses current fillStyle
ctx.beginPath();
ctx.arc(250, 90, 40, 0, 2 * Math.PI);
ctx.strokeStyle = "steelblue";
ctx.lineWidth = 6;
ctx.stroke();
Path operations are accumulated; remember to call ctx.beginPath() for a fresh shape.
Creating fills and strokes beyond solid colors.
const grad = ctx.createLinearGradient(0, 0, 0, 200);
grad.addColorStop(0, "#ff9a9e");
grad.addColorStop(1, "#fad0c4");
ctx.fillStyle = grad;
ctx.fillRect(0, 0, 200, 200);
const img = new Image();
img.src = "tiles.png";
img.onload = () => {
const patt = ctx.createPattern(img, "repeat");
ctx.fillStyle = patt;
ctx.fillRect(220, 0, 200, 200);
};
Drawing dynamic text with styling.
ctx.font = "bold 32px system-ui";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#fff";
ctx.fillText("Hello Canvas!", canvas.width/2, canvas.height/2);
ctx.strokeStyle = "#222";
ctx.lineWidth = 2;
ctx.strokeText("Outlines, too", 320, 300);
Measure before placement with ctx.measureText(text).width.
Blitting external sources and cropping.
const hero = new Image();
hero.src = "sprite.png";
hero.onload = () => {
// draw a frame 32×32 from (col = 1, row = 0)
ctx.drawImage(hero,
32, 0, 32, 32, // sx, sy, sw, sh
100, 100, 64, 64 // dx, dy, dw, dh
);
};
// Streams: paint a <video> every frame
function tick(){
ctx.drawImage(videoEl, 0, 0);
requestAnimationFrame(tick);
}
Reading and writing raw RGBA data.
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imgData.data; // Uint8ClampedArray [ r, g, b, a, … ]
for(let i = 0; i < data.length; i += 4){
const gray = data[i]*0.21 + data[i+1]*0.72 + data[i+2]*0.07;
data[i] = data[i+1] = data[i+2] = gray; // desaturate
}
ctx.putImageData(imgData, 0, 0);
Pixel ops are CPU-heavy. Prefer OffscreenCanvas + Workers or WebGL shaders for real-time filters.
Scaling, rotation, clipping, and blend modes.
ctx.translate(cx, cy);
ctx.rotate(angle);
ctx.scale(scaleX, scaleY);
ctx.clip(); // use current path as clip mask
ctx.globalCompositeOperation = "multiply"; // over, screen, overlay…
Running at the display’s refresh rate or fixed steps.
let last = performance.now();
function loop(time){
const dt = (time - last) / 1000; // seconds
last = time;
ctx.clearRect(0, 0, canvas.width, canvas.height);
update(dt); draw();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
For physics stability, update logic with a fixed step (e.g., 60 Hz) and interpolate during render.
Parallel rendering, bitmap transfer, and resolution scaling.
// main thread
const off = canvas.transferControlToOffscreen();
worker.postMessage({ canvas: off }, [off]);
// worker.js
onmessage = ({ data }) => {
const ctx = data.canvas.getContext("2d");
render(ctx);
};
Moving to GPU pipelines inside <canvas>.
Request with getContext("webgl2").
Draw calls are retained by the GPU until gl.flush().
Use shaders (.vert
, .frag
) and buffer objects.
const gl = canvas.getContext("webgl2");
const vs = `#version 300 es
in vec2 pos; void main(){ gl_Position = vec4(pos,0,1);} `;
const fs = `#version 300 es
precision mediump float; out vec4 col; void main(){ col = vec4(1,0,0,1);} `;
// compile, link, drawArrays(GL_TRIANGLES)…
Maintainability, accessibility, and tooling.
<canvas>…</canvas>
for
screen readers.A detailed guide covering essential Canvas methods and parameters.
fillRect(x, y, width, height)
Draws a filled rectangle. Parameters specify position and dimensions.
strokeRect(x, y, width, height)
Draws an outlined rectangle with the current stroke style.
clearRect(x, y, width, height)
Clears a rectangular area, making it fully transparent.
beginPath()
Starts a new drawing path.
moveTo(x, y)
Moves the drawing cursor to the specified coordinates.
lineTo(x, y)
Draws a straight line from the current position to the specified coordinates.
arc(x, y, radius, startAngle, endAngle, [anticlockwise])
Draws a circular arc centered at (x, y). Angles are in radians.
closePath()
Connects the last point of the path with the first point.
stroke()
Strokes the current path with the current stroke style.
fill()
Fills the current path with the current fill style.
fillStyle = color | gradient | pattern
Specifies the color or style to fill shapes.
strokeStyle = color | gradient | pattern
Defines the color or style to stroke paths.
lineWidth = number
Sets the thickness of lines.
createLinearGradient(x0, y0, x1, y1)
Creates a linear gradient object.
addColorStop(offset, color)
Adds a color stop to gradients. Offset ranges from 0.0 to 1.0.
fillText(text, x, y, [maxWidth])
Draws filled text at the given coordinates.
strokeText(text, x, y, [maxWidth])
Draws outlined text.
measureText(text)
Returns an object containing text metrics (width).
drawImage(image, dx, dy, [dw, dh])
Draws an image at (dx, dy), optionally scaled to dw, dh.
drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
Draws a subsection of the image (source rectangle) scaled to destination rectangle.
getImageData(x, y, width, height)
Extracts pixel data from the canvas area specified.
putImageData(imageData, x, y)
Draws pixel data onto the canvas at position x, y.
translate(x, y)
Moves the canvas origin to the specified coordinates.
rotate(angle)
Rotates the canvas clockwise by the angle (in radians).
scale(x, y)
Scales the canvas units by x and y factors.
save()
Saves the current state (transformations, styles).
restore()
Restores to the previously saved state.
resetTransform()
Resets transformations to default.
requestAnimationFrame(callback)
Queues animation callback to run at display refresh rate.
Use this guide as a reference for building efficient and interactive graphics applications with Canvas in JavaScript.
Scrollable grid of rendered frames.