Cheatsheet: HTML5 Canvas

Basic Setup

Create a Canvas element

<canvas id="myCanvas" width="500" height="500"></canvas>

Get Canvas Context

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

Drawing Shapes

Draw a Rectangle

ctx.fillStyle = 'red';
ctx.fillRect(20, 20, 150, 100);

Draw a Circle

ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();

Draw a Line

ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();

Text

Draw Text

ctx.font = '30px Arial';
ctx.fillText('Hello World', 10, 50);

Outline Text

ctx.font = '30px Arial';
ctx.strokeText('Hello World', 10, 50);

Images

Draw an Image

const img = new Image();
img.onload = function() {
  ctx.drawImage(img, 0, 0);
};
img.src = 'path/to/image.jpg';

Draw Part of an Image

ctx.drawImage(img, 10, 10, 100, 100, 20, 20, 200, 200);

Transformations

Scale

ctx.scale(2, 2);
ctx.fillRect(10, 10, 50, 50);

Rotate

ctx.rotate((Math.PI / 180) * 25);
ctx.fillRect(50, 20, 100, 50);

Translate

ctx.translate(70, 70);
ctx.fillRect(0, 0, 50, 50);

Cookbook

Draw an arrow

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

// Function to draw a curved arrow
function drawCurvedArrow(ctx, fromX, fromY, toX, toY, controlX, controlY, text) {
    // Draw the curved line
    ctx.beginPath();
    ctx.moveTo(fromX, fromY);
    ctx.quadraticCurveTo(controlX, controlY, toX, toY);
    ctx.stroke();

    // Draw the arrowhead
    const headlen = 10; // Length of the arrow head
    const angle = Math.atan2(toY - controlY, toX - controlX);
    ctx.beginPath();
    ctx.moveTo(toX, toY);
    ctx.lineTo(toX - headlen * Math.cos(angle - Math.PI / 6), toY - headlen * Math.sin(angle - Math.PI / 6));
    ctx.moveTo(toX, toY);
    ctx.lineTo(toX - headlen * Math.cos(angle + Math.PI / 6), toY - headlen * Math.sin(angle + Math.PI / 6));
    ctx.stroke();

    // Draw the label
    const midX = (fromX + toX) / 2;
    const midY = (fromY + toY) / 2;
    ctx.font = '16px Arial';
    ctx.fillText(text, midX, midY);
}

// Example usage
drawCurvedArrow(ctx, 50, 150, 200, 150, 125, 50, 'Curved Arrow');