HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

HTML Canvas

The HTML5 <canvas> element is exactly what it sounds like—a blank rectangular space on your web page that acts as a true digital canvas. By itself, the canvas does absolutely nothing. No borders, no colors, no text.

To produce graphics, you must write a JavaScript script that actively "paints" pixels, shapes, lines, images, or even fully interactive 3D video Games onto that canvas.


Setting Up the Canvas

Creating the physical canvas is easy. You define the width, height, and adding an id so that JavaScript can easily locate it later.

<!-- A simple 300x150 canvas with an added CSS border so you can see it -->
<canvas id="myCanvas" width="300" height="150" style="border: 1px solid #000;">
  Your browser does not support the HTML canvas tag.
</canvas>

Drawing with JavaScript

The canvas has a built-in object called the Context. Think of the Context as your virtual paintbrush and palette combined. The most common context type is "2d".

1. Drawing a Filled Rectangle

Let's find the canvas from the HTML above, equip our 2D paintbrush, and draw a solid red square inside it.

<script>
// 1. Find the canvas element
var c = document.getElementById("myCanvas");

// 2. Obtain the 2D drawing tool (paintbrush)
var ctx = c.getContext("2d");

// 3. Set the fill color to red
ctx.fillStyle = "#FF0000";

// 4. Draw the rectangle (x, y, width, height)
ctx.fillRect(20, 20, 100, 100);
</script>

2. Drawing Lines

To draw a line, you have to imagine you are holding a physical pen above the paper. You move the pen to a starting point (moveTo), trace an invisible line to the end point (lineTo), and then apply ink (stroke) to make the line visible.

<script>
var c = document.getElementById("myCanvas2");
var ctx = c.getContext("2d");

// Move the starting point to X:0, Y:0 (Top-left corner)
ctx.moveTo(0, 0);

// Trace a line to X:300, Y:150 (Bottom-right corner)
ctx.lineTo(300, 150);

// Provide ink to trace the path we just created
ctx.stroke();
</script>

3. Drawing Circles / Arcs

To draw a perfect circle, you use the arc() method, which asks for the X and Y coordinate of the center point, the radius, the starting angle, and the ending angle (using Math.PI).

<script>
var ctx = c.getContext("2d");
ctx.beginPath();

// arc(x, y, radius, startAngle, endAngle)
ctx.arc(150, 75, 40, 0, 2 * Math.PI);
ctx.stroke();
</script>
Canvas vs SVG: While a Canvas uses JavaScript to paint pixels permanently onto a grid, SVG (Scalable Vector Graphics) uses XML tags to build shapes that act like real DOM elements. If you zoom into a Canvas it gets blurry (pixelated), but an SVG will stay beautifully sharp forever. SVG is better for logos, while Canvas is better for complex physics simulations and video games!