create a canvas element and draw an orange square in typescript

index.ts
// Get the canvas element from the DOM
const canvas: HTMLCanvasElement = document.getElementById("canvas") as HTMLCanvasElement;

// Get the 2D rendering context of the canvas
const ctx: CanvasRenderingContext2D = canvas.getContext("2d") as CanvasRenderingContext2D;

// Set the fill color to orange
ctx.fillStyle = "orange";

// Draw a square with a side length of 50 pixels at (50, 50)
ctx.fillRect(50, 50, 50, 50);
418 chars
12 lines

Explanation:

  1. To create a canvas element, you first need to get it from the DOM using document.getElementById().
  2. To draw on the canvas, you need to get the 2D rendering context of the canvas using canvas.getContext("2d").
  3. To set the fill color of the square, use ctx.fillStyle.
  4. To draw a square on the canvas, use ctx.fillRect(x, y, width, height). The x and y parameters specify the top-left corner of the square, while the width and height parameters specify the size of the square.

gistlibby LogSnag