HTML5 Canvas / JavaScript Cheat Sheet
A one-page printable reference for Canvas setup, drawing, game loop, input, images, audio, math, collision and common JS game patterns. Pin it next to your monitor!
A one-page printable reference for Canvas setup, drawing, game loop, input, images, audio, math, collision and common JS game patterns. Pin it next to your monitor!
const canvas = document .getElementById("game"); const ctx = canvas.getContext("2d"); canvas.width = 800; canvas.height = 600; // optional: pixel-art scaling canvas.style.imageRendering = "pixelated";
let lastTime = 0; function gameLoop(timestamp) { const dt = (timestamp - lastTime) / 1000; // delta in seconds lastTime = timestamp; update(dt); ctx.clearRect(0, 0, canvas.width, canvas.height); draw(); requestAnimationFrame(gameLoop); } requestAnimationFrame(gameLoop);
| ctx.fillRect(x,y,w,h) | Fill a rectangle |
| ctx.strokeRect(x,y,w,h) | Stroke rectangle outline |
| ctx.fillRect(arc circle) | Manual: arc + fill |
| ctx.drawImage(img,x,y,w,h) | Draw image / sprite |
| ctx.fillText(str,x,y) | Draw text |
| ctx.beginPath() | Start a new path |
| ctx.arc(x,y,r,0,Math.PI*2) | Circle path |
| ctx.closePath() | Close current path |
ctx.fillStyle = "#ff77a8"; ctx.strokeStyle = "#ffffff"; ctx.lineWidth = 2; ctx.font = "16px monospace";
const img = new Image(); img.src = "sprite.png"; img.onload = () => { // ready to draw }; # draw full image ctx.drawImage(img, x, y); # draw with size ctx.drawImage(img, x, y, 64, 64); # draw sprite sheet region ctx.drawImage(img, sx, sy, sw, sh, # source rect dx, dy, dw, dh # dest rect );
const sfx = new Audio("jump.mp3"); sfx.play(); const bgm = new Audio("music.mp3"); bgm.loop = true; bgm.volume = 0.3; bgm.play(); bgm.pause(); bgm.currentTime = 0; # rewind # prevent overlap on fast fire const shoot = () => { sfx.currentTime = 0; sfx.play(); };
# keyboard map pattern const keys = {}; document.addEventListener("keydown", e => keys[e.code] = true); document.addEventListener("keyup", e => keys[e.code] = false); # usage if (keys["ArrowLeft"]) x -= 5; if (keys["ArrowRight"]) x += 5; if (keys["Space"]) shoot(); # mouse canvas.addEventListener("mousedown", e => { /* click */ }); canvas.addEventListener("mousemove", e => { mouseX = e.offsetX; mouseY = e.offsetY; });
| Math.abs(n) | Absolute value |
| Math.sqrt(n) | Square root |
| Math.atan2(dy, dx) | Angle from direction |
| Math.floor(n) | Round down to int |
| Math.ceil(n) | Round up to int |
| Math.random() | Random float [0, 1) |
| Math.min(a, b) | Minimum of two values |
| Math.max(a, b) | Maximum of two values |
const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a; const dist = Math.sqrt( dx*dx + dy*dy);
# AABB (axis-aligned bounding box) function aabb(a, b) { return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y; } # circle-circle function circCollide(a, b) { const dx = a.x - b.x; const dy = a.y - b.y; return dx*dx + dy*dy < (a.r + b.r) ** 2; } # point-rect function pointInRect(px, py, r) { return px >= r.x && px <= r.x + r.w && py >= r.y && py <= r.y + r.h; }
โโ ENTITY SYSTEM โโ class Entity { constructor(x, y, w, h) { this.x = x; this.y = y; this.w = w; this.h = h; this.dx = 0; this.dy = 0; this.alive = true; } update(dt) {} draw(ctx) {} } const entities = []; # update all: entities.forEach(e => e.update(dt)) # remove dead: entities = entities.filter(e => e.alive) โโ SPRITE SHEET ANIMATION โโ const frameW = 32, frameH = 32; let frame = 0, timer = 0; const animSpeed = 0.15; timer += dt; if (timer >= animSpeed) { timer = 0; frame = (frame + 1) % totalFrames; } ctx.drawImage(sheet, frame * frameW, 0, frameW, frameH, x, y, frameW, frameH); โโ PARTICLE SYSTEM โโ const particles = []; function spawn(x, y, n = 10) { for (let i = 0; i < n; i++) { particles.push({ x, y, vx: (Math.random() - .5) * 6, vy: (Math.random() - .5) * 6, life: 1 }); } } # update: p.x += p.vx; p.life -= dt; # draw: ctx.globalAlpha = p.life; โโ CAMERA โโ const cam = { x: 0, y: 0 }; cam.x = player.x - canvas.width / 2; cam.y = player.y - canvas.height / 2; ctx.save(); ctx.translate(-cam.x, -cam.y); # draw world ctx.restore(); โโ SCROLLING BACKGROUND โโ let bgX = 0; bgX -= 2; if (bgX <= -canvas.width) bgX += canvas.width; ctx.drawImage(bg, bgX, 0); ctx.drawImage(bg, bgX + canvas.width, 0); โโ BUTTON / UI SYSTEM โโ function drawBtn(x, y, w, h, label) { ctx.fillStyle = "#ff77a8"; ctx.fillRect(x, y, w, h); ctx.fillStyle = "white"; ctx.fillText(label, x + w/2, y + h/2 + 6); } function btnClick(mx, my, b) { return mx >= b.x && mx <= b.x + b.w && my >= b.y && my <= b.y + b.h; }
Follow one of our free step-by-step workshops in the Workshop hub.
๐ง Browse Workshops โ