HTML5
Canvas Basics
Draw shapes, lines, and text on a 2D canvas.
By EZ4Code Team
canvasgraphics
Code
<canvas id="cv" width="300" height="200"></canvas>
<script>
const canvas = document.getElementById("cv");
const ctx = canvas.getContext("2d");
// Rectangle
ctx.fillStyle = "#1976d2";
ctx.fillRect(10, 10, 100, 50);
// Line
ctx.beginPath();
ctx.moveTo(20, 100);
ctx.lineTo(200, 150);
ctx.strokeStyle = "red";
ctx.stroke();
// Circle
ctx.beginPath();
ctx.arc(220, 80, 40, 0, Math.PI * 2);
ctx.fillStyle = "green";
ctx.fill();
// Text
ctx.font = "16px sans-serif";
ctx.fillText("Hello Canvas", 50, 180);
</script>Explanation
The canvas element provides a scriptable bitmap drawing surface via a 2D context. fillRect, arc, and fillText draw shapes and text, while beginPath groups connected drawing commands. Canvas is ideal for games and charts but is resolution-dependent and not vector-based like SVG.
More HTML5 Snippets
Semantic Elements
Structure a page with header, nav, main, article, and footer.
Form Input Types
Use native HTML5 input types, validation, and datalist.
Video & Audio
Embed media with multiple sources and control playback.
Local & Session Storage
Persist data in the browser with the Web Storage API.
Geolocation
Get the user's position and watch for changes.
Drag and Drop
Accept dropped files with the Drag and Drop API.