HTML — Lesson 23
HTML Canvas Basics
Drawing graphics and animations with the HTML Canvas API.
HTML Canvas Basics
The <canvas> element provides a drawable region in HTML. You use JavaScript to draw shapes, text, images, and animations on it.
Creating a Canvas
<canvas id="myCanvas" width="500" height="300"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
</script>
Drawing Shapes
// Rectangle
ctx.fillStyle = "#4ecdc4";
ctx.fillRect(10, 10, 150, 100);
// Outlined rectangle
ctx.strokeStyle = "#333";
ctx.lineWidth = 2;
ctx.strokeRect(200, 10, 150, 100);
// Circle
ctx.beginPath();
ctx.arc(400, 60, 40, 0, Math.PI * 2);
ctx.fillStyle = "#ff6b6b";
ctx.fill();
Drawing Paths
// Triangle
ctx.beginPath();
ctx.moveTo(250, 150);
ctx.lineTo(300, 250);
ctx.lineTo(200, 250);
ctx.closePath();
ctx.fillStyle = "#764ba2";
ctx.fill();
Drawing Text
ctx.font = "bold 32px Arial";
ctx.fillStyle = "#333";
ctx.fillText("Hello Canvas!", 50, 280);
ctx.font = "16px Arial";
ctx.strokeStyle = "#666";
ctx.strokeText("Outlined text", 50, 290);
Simple Animation
<canvas id="myCanvas" width="400" height="200"
style="border:1px solid #ccc;"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
let x = 50;
let speed = 2;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#ff6b6b";
ctx.beginPath();
ctx.arc(x, 100, 25, 0, Math.PI * 2);
ctx.fill();
x += speed;
if (x > 375 || x < 25) speed = -speed;
requestAnimationFrame(animate);
}
animate();
</script>
Tip: Use
requestAnimationFrame() for smooth animations instead of setInterval(). It syncs with the browser's refresh rate for optimal performance.
Practice what you learned in the Deoit Editor — a free, browser-based code editor.
Open Editor →