HTMLCanvasElement
Canvas Element
Represents a <canvas> tag. A drawable surface — you get a drawing context from it and use that to draw shapes, images, and text with JavaScript.
<canvas
width="800"
height="400"
></canvas>
Key Properties
| Property | Type | Description |
|---|---|---|
| width | number | Drawing surface width in pixels. Setting this clears the canvas. |
| getContext() | context | Returns the drawing API. Pass "2d" for 2D graphics, "webgl" for 3D. |
| toDataURL() | string | Exports the canvas as a base64 image string (PNG by default). |
Quick Examples
JS
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
// Draw a circle
ctx.beginPath();
ctx.arc(200, 200, 80, 0, Math.PI * 2);
ctx.fillStyle = '#4361ee';
ctx.fill();
// Draw an image onto canvas
const img = new Image();
img.src = 'photo.jpg';
img.onload = () => ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// Clear everything
ctx.clearRect(0, 0, canvas.width, canvas.height);Related Elements
Related Properties
Related Methods