Canvas Pattern

What You’ll Learn
Canvas patterns let you fill shapes with repeating textures. A pattern can come from an image, a video frame, or even another canvas.
On this page you’ll learn createPattern(), repetition modes, and how to scale/rotate patterns.
⚡ Quick Reference
const tile = document.createElement('canvas'); // or an Image()
const pattern = ctx.createPattern(tile, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);repeatX + Y repeat
repeat-xRepeat horizontally only
repeat-yRepeat vertically only
no-repeatNo repetition
👀 Live Preview — Repeat & Scale
This preview generates a small tile canvas, turns it into a pattern, then fills the main canvas. Adjust repetition, tile size, and pattern scale.
Tip: For crisp pixel-art patterns, turn smoothing off and avoid fractional scaling.
Fill Canvas with an Image Pattern
This is the classic pattern flow: load an image, create a pattern, then fill a rectangle.
const img = new Image();
img.onload = () => {
const pattern = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);
};
img.src = '/images/tile.png';Pattern from an Offscreen Canvas (No Image Needed)
You can generate a tile using another canvas. This avoids image loading and is great for procedural textures.
const tile = document.createElement('canvas');
tile.width = 24;
tile.height = 24;
const t = tile.getContext('2d');
// draw a simple tile (dot)
t.fillStyle = '#fff';
t.fillRect(0, 0, 24, 24);
t.fillStyle = '#2563eb';
t.beginPath();
t.arc(8, 8, 4, 0, Math.PI * 2);
t.fill();
const pattern = ctx.createPattern(tile, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);💡 Best Practices
Do
- Use small tiles (like 16–64px) for efficient repeating textures
- Use offscreen canvas tiles for procedural patterns (no loading)
- Reset transforms with
save()/restore()when scaling/rotating patterns - Turn smoothing off for crisp pixel tiles (especially when scaling)
- Test repeat modes (
repeat-x,repeat-y,no-repeat) for your layout
Don’t
- Use huge tiles for simple textures (wastes memory and bandwidth)
- Forget image loading: createPattern needs a ready image/canvas
- Leave transforms active and wonder why later drawings are scaled
- Over-scale low-res tiles without expecting blur
- Confuse
no-repeatwith repeating vertically (it means no repeat)
❓ Frequently Asked Questions
fillStyle or strokeStyle.repeat, repeat-x, repeat-y, and no-repeat.pattern.setTransform().Next: Radial Gradients
Create center-out glows and spotlights with createRadialGradient().
4 people found this page helpful
