learn2kode.in

HTML Canvas

The <canvas> element in HTML is used to draw graphics dynamically using JavaScript.
It is widely used for:

Canvas provides a pixel-based drawing surface, unlike SVG which is vector-based.

Basic Canvas Syntax

<canvas id="myCanvas" width="300" height="150"></canvas>

Without JavaScript, a canvas will remain blank.

Drawing on Canvas Using JavaScript

Here is a simple example that draws a blue line:

<!DOCTYPE html>
<html>
<body>

<h2>Canvas Example</h2>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000;"></canvas>

<script>
  let canvas = document.getElementById("myCanvas");
  let ctx = canvas.getContext("2d");

  // Draw a line
  ctx.beginPath();
  ctx.moveTo(10, 10);
  ctx.lineTo(200, 100);
  ctx.strokeStyle = "blue";
  ctx.lineWidth = 3;
  ctx.stroke();
</script>

</body>
</html>

1. Drawing Shapes

2. Colors & Styles

3. Text

4. Images

5. Animation