Key Properties
PropertyTypeDescription
widthnumber Drawing surface width in pixels. Setting this clears the canvas. ▾

Note: this is the canvas resolution, not the CSS display size. Use CSS for display size.

JS
canvas.width = 1200;   // resolution
canvas.height = 600;
canvas.style.width = '600px';  // display size (CSS)
getContext()context Returns the drawing API. Pass "2d" for 2D graphics, "webgl" for 3D. ▾

This is the most important method — everything you draw goes through the context object it returns.

JS
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');

// Now draw with ctx:
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 50);   // x, y, width, height

ctx.strokeStyle = 'blue';
ctx.lineWidth = 3;
ctx.strokeRect(10, 10, 100, 50);

ctx.fillStyle = 'black';
ctx.font = '20px sans-serif';
ctx.fillText('Hello!', 10, 100);
toDataURL()string Exports the canvas as a base64 image string (PNG by default). ▾
JS
const dataURL = canvas.toDataURL('image/png');

// Use it as an image src
const img = document.createElement('img');
img.src = dataURL;

// Or trigger a download
const a = document.createElement('a');
a.href = dataURL;
a.download = 'drawing.png';
a.click();
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