The Canvas API gives JavaScript direct pixel-level drawing control — the foundation for browser-based games, data visualizations, and image editing tools that don’t rely on SVG or DOM elements.
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
// Basic shapes
ctx.fillStyle = '#3858e9';
ctx.fillRect(10, 10, 100, 50);
ctx.beginPath();
ctx.arc(200, 100, 40, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
// A simple animation loop
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // clear the previous frame
ctx.fillRect(x, 50, 20, 20);
x = (x + 2) % canvas.width;
requestAnimationFrame(animate); // synced to the browser's repaint rate
}
animate();
requestAnimationFrame is the key detail — it schedules the callback right before the browser’s next repaint, syncing your animation to the display’s actual refresh rate (typically 60fps), which setInterval can’t reliably guarantee.