JavaScript HTML Canvas

The HTML Canvas element provides a drawing surface that JavaScript can use to render graphics, animations, and visualizations. The Canvas API offers methods for drawing shapes, lines, text, and images programmatically.

The Canvas Element and getContext()

To draw on a canvas, you first get a reference to the canvas element, then call getContext('2d') to get the 2D rendering context. All drawing operations are performed on this context.

Setting Up Canvas
// HTML: <canvas id="myCanvas" width="400" height="300"></canvas>

// const canvas = document.getElementById('myCanvas');
// const ctx = canvas.getContext('2d');

// Canvas properties
console.log('Canvas is a drawing surface in HTML');
console.log('getContext("2d") for 2D graphics');
console.log('getContext("webgl") for 3D graphics');

// Default canvas size is 300x150
// Always set width/height via attributes, not CSS
console.log('\nDefault size: 300 x 150 pixels');
console.log('Set size via width/height attributes');
console.log('CSS sizing distorts the canvas');

Drawing Rectangles

The Canvas API provides three methods for drawing rectangles: fillRect() for filled rectangles, strokeRect() for outlined rectangles, and clearRect() to clear an area.

fillRect() and strokeRect()
// const canvas = document.getElementById('myCanvas');
// const ctx = canvas.getContext('2d');

// fillRect(x, y, width, height) - filled rectangle
// ctx.fillStyle = 'blue';
// ctx.fillRect(10, 10, 100, 50);

// strokeRect(x, y, width, height) - outlined rectangle
// ctx.strokeStyle = 'red';
// ctx.lineWidth = 2;
// ctx.strokeRect(130, 10, 100, 50);

// clearRect(x, y, width, height) - clears an area
// ctx.clearRect(30, 20, 40, 20);

console.log('fillRect(x, y, w, h) - filled rectangle');
console.log('strokeRect(x, y, w, h) - outlined rectangle');
console.log('clearRect(x, y, w, h) - erase an area');
console.log('\nfillStyle sets fill color');
console.log('strokeStyle sets outline color');
console.log('lineWidth sets outline thickness');

Drawing Paths and Lines

Paths are used to draw lines, arcs, and complex shapes. You begin a path with beginPath(), define it with moveTo() and lineTo(), and then render it with stroke() or fill().

Lines and Paths
// Drawing a triangle with paths
// ctx.beginPath();
// ctx.moveTo(100, 10);     // Move pen to start point
// ctx.lineTo(50, 100);     // Line to bottom-left
// ctx.lineTo(150, 100);    // Line to bottom-right
// ctx.closePath();          // Close the triangle
// ctx.strokeStyle = 'green';
// ctx.lineWidth = 3;
// ctx.stroke();             // Draw the outline

console.log('Path drawing steps:');
console.log('1. ctx.beginPath()     - start new path');
console.log('2. ctx.moveTo(x, y)    - move pen');
console.log('3. ctx.lineTo(x, y)    - draw line to point');
console.log('4. ctx.closePath()     - close the shape');
console.log('5. ctx.stroke()        - draw outline');
console.log('   ctx.fill()          - fill shape');

console.log('\nLine styles:');
console.log('lineCap: butt, round, square');
console.log('lineJoin: miter, round, bevel');

Drawing Arcs and Circles

The arc() method draws arcs and circles. It takes center coordinates, radius, start angle, end angle, and direction.

Arcs and Circles
// arc(x, y, radius, startAngle, endAngle, counterclockwise)

// Full circle
// ctx.beginPath();
// ctx.arc(100, 100, 50, 0, Math.PI * 2);
// ctx.fillStyle = 'orange';
// ctx.fill();

// Half circle (semicircle)
// ctx.beginPath();
// ctx.arc(250, 100, 50, 0, Math.PI);
// ctx.stroke();

// Quarter circle
// ctx.beginPath();
// ctx.arc(100, 200, 50, 0, Math.PI / 2);
// ctx.stroke();

console.log('arc(x, y, radius, startAngle, endAngle)');
console.log('Angles are in radians, not degrees');
console.log('');
console.log('Common angles:');
console.log('  Full circle:  0 to ' + (Math.PI * 2).toFixed(4) + ' (2PI)');
console.log('  Half circle:  0 to ' + Math.PI.toFixed(4) + ' (PI)');
console.log('  Quarter:      0 to ' + (Math.PI / 2).toFixed(4) + ' (PI/2)');
console.log('\nDeg to Rad: degrees * (Math.PI / 180)');

Colors, Styles, and Text

Canvas supports various color formats, gradients, and text rendering. fillStyle and strokeStyle accept color strings, gradients, and patterns.

Colors and Text
// Colors can be: names, hex, rgb, rgba, hsl
// ctx.fillStyle = 'red';
// ctx.fillStyle = '#FF0000';
// ctx.fillStyle = 'rgb(255, 0, 0)';
// ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';

// Drawing text
// ctx.font = '24px Arial';
// ctx.fillStyle = 'black';
// ctx.fillText('Hello Canvas!', 50, 50);
// ctx.strokeText('Outlined Text', 50, 100);

// Text alignment
// ctx.textAlign = 'center';  // left, right, center
// ctx.textBaseline = 'middle';  // top, middle, bottom

console.log('Text methods:');
console.log('  fillText(text, x, y) - filled text');
console.log('  strokeText(text, x, y) - outlined text');
console.log('  measureText(text) - get text width');

console.log('\nText properties:');
console.log('  font, textAlign, textBaseline');
console.log('  direction (ltr, rtl)');

clearRect() and Refreshing the Canvas

clearRect() erases a rectangular area of the canvas. To clear the entire canvas (for animations), clear the full dimensions.

Clearing the Canvas
// Clear the entire canvas
// ctx.clearRect(0, 0, canvas.width, canvas.height);

// Animation loop pattern
// function animate() {
//   ctx.clearRect(0, 0, canvas.width, canvas.height);
//   // Draw new frame
//   drawScene();
//   requestAnimationFrame(animate);
// }
// animate();

console.log('Animation pattern:');
console.log('1. Clear the canvas');
console.log('2. Draw the new frame');
console.log('3. Request next animation frame');
console.log('4. Repeat');

console.log('\nrequestAnimationFrame() is preferred over');
console.log('setInterval() for smooth animations');
console.log('It syncs with the display refresh rate (~60fps)');
MethodDescription
fillRect(x,y,w,h)Draw a filled rectangle
strokeRect(x,y,w,h)Draw rectangle outline
clearRect(x,y,w,h)Clear a rectangular area
beginPath()Start a new path
moveTo(x,y)Move drawing cursor
lineTo(x,y)Draw line to point
arc(x,y,r,start,end)Draw an arc or circle
fill()Fill the current path
stroke()Outline the current path
fillText(text,x,y)Draw filled text
strokeText(text,x,y)Draw text outline
📝 Note: Canvas is pixel-based (raster), not vector-based like SVG. This means canvas graphics do not scale well when zoomed. For scalable graphics, consider SVG. For complex animations and games, Canvas with requestAnimationFrame() is typically the better choice due to better performance.
Exercise:
What method do you call to get the 2D drawing context from a canvas element?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.