HTML Canvas Graphics

🎨 HTML Canvas Graphics

The HTML <canvas> element is used to draw graphics using JavaScript.

It is powerful for creating shapes, charts, games, animations, and visual effects directly in the browser.


 1. What Is HTML Canvas?

  • <canvas> is a bitmap drawing area

  • Graphics are drawn using JavaScript

  • Used for 2D graphics (and with libraries, 3D too)

  • No drawing by itself → JS is required

<canvas id="myCanvas"></canvas>

 2. Basic Canvas Setup

HTML

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

JavaScript

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

getContext("2d") gives the drawing tool


 3. Drawing a Line

<script>
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
</script>

moveTo() → starting point
lineTo() → ending point
stroke() → draws the line


 4. Drawing a Rectangle

▶️ Stroke Rectangle

ctx.strokeRect(20, 20, 150, 100);

▶️ Filled Rectangle

ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 150, 100);

 5. Drawing a Circle (Arc)

ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();

arc(x, y, radius, startAngle, endAngle)


 6. Drawing Text

▶️ Fill Text

ctx.font = "20px Arial";
ctx.fillText("Hello Canvas", 50, 50);

▶️ Stroke Text

ctx.strokeText("Hello Canvas", 50, 80);

 7. Adding Colors & Styles

ctx.strokeStyle = "red";
ctx.lineWidth = 3;
ctx.fillStyle = "green";

 8. Drawing an Image

<img id="img" src="image.png" style="display:none;">

<script>
const img = document.getElementById(“img”);
img.onload = function () {
ctx.drawImage(img, 10, 10, 100, 100);
};
</script>

✔ Used for games & graphics


 9. Canvas Coordinates System

  • Top-left corner = (0, 0)

  • X-axis → right

  • Y-axis → down

📌 All drawing is based on this coordinate system.


 10. Simple Animation (Basic Example)

<script>
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 50, 50, 50);
x += 2;
requestAnimationFrame(animate);
}animate();
</script>

✔ Smooth animation
✔ Used in games & motion graphics


 11. Canvas vs SVG (Quick Comparison)

Feature Canvas SVG
Rendering Bitmap Vector
Scalability
Performance High Medium
Animations JS-based CSS/SMIL
Best for Games, charts Icons, diagrams

❌ Common Mistakes

❌ Forgetting to set width & height
❌ Trying to draw without JavaScript
❌ Not clearing canvas in animations
❌ Expecting canvas content to be accessible by default


🧠 Key Points to Remember

  • <canvas> is drawn using JavaScript

  • Uses a coordinate system

  • Perfect for graphics & games

  • Needs manual redraw

  • High performance rendering

You may also like...