Let’s begin with Lecture 41 of the HTML5 & CSS3 series. Advanced Canvas Features – Gradients, Images & Simple Games. This lecture is for absolute beginners; even kids can follow along and understand.
🎯 Objective:
By the end of this lecture, you will:
- Understand how to use gradients (linear and radial) in HTML5 Canvas
- Know how to draw images on canvas
- Be able to create simple animations or games like clickable shapes
- Learn how to detect mouse clicks inside canvas elements
- Build a fun interactive drawing or game using advanced Canvas features!
🌈 Using Gradients in Canvas
Gradients let you fill shapes with smooth color transitions.
There are two types:
1. Linear Gradient
Draws a gradient in a straight line.
let gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, "red");
gradient.addColorStop(1, "yellow");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 100);
2. Radial Gradient
Draws a circular gradient (like a spotlight).
let gradient = ctx.createRadialGradient(100, 100, 10, 100, 100, 80);
gradient.addColorStop(0, "white");
gradient.addColorStop(1, "blue");
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(100, 100, 80, 0, Math.PI * 2);
ctx.fill();
🖼️ Drawing Images on Canvas
You can draw images from your computer or the web onto the canvas.
Example:
<img id="myImage" src="https://picsum.photos/id/237/200/150 " style="display: none;">
let img = document.getElementById("myImage");
img.onload = function() {
ctx.drawImage(img, 50, 50); // Draw image at (50,50)
};
You can also resize it:
ctx.drawImage(img, 50, 50, 100, 75); // x, y, width, height
🕹️ Detecting Mouse Clicks Inside Canvas
Canvas is just one big area — so you need to calculate where the user clicked.
Basic Setup:
canvas.addEventListener("click", function(event) {
let rect = canvas.getBoundingClientRect();
let mouseX = event.clientX - rect.left;
let mouseY = event.clientY - rect.top;
console.log("Clicked at:", mouseX, mouseY);
});
Now you can check if the click was inside a shape — perfect for making clickable buttons or game objects!
💻 Try This: Create a Colorful Gradient Background
Let’s make a background that smoothly changes colors across the screen.
Step 1: Open Your Canvas File
Go back to canvas-drawing.html
or open a new file named:
gradient-canvas.html
Step 2: Add This Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas Gradient</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script>
let canvas = document.getElementById("myCanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let ctx = canvas.getContext("2d");
// Create linear gradient background
let gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, "#ff9a9e");
gradient.addColorStop(0.5, "#fad0c4");
gradient.addColorStop(1, "#fad0c4");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw a circle that responds to clicks
let circleX = 300;
let circleY = 200;
let circleRadius = 50;
function drawCircle() {
ctx.beginPath();
ctx.arc(circleX, circleY, circleRadius, 0, Math.PI * 2);
ctx.fillStyle = "#3498db";
ctx.fill();
ctx.closePath();
}
drawCircle();
canvas.addEventListener("click", function(event) {
let rect = canvas.getBoundingClientRect();
let mouseX = event.clientX - rect.left;
let mouseY = event.clientY - rect.top;
// Check if click is inside the circle
let dx = mouseX - circleX;
let dy = mouseY - circleY;
let distance = Math.sqrt(dx * dx + dy * dy);
if (distance < circleRadius) {
alert("You clicked the circle! 😄");
}
});
</script>
</body>
</html>
🎉 You’ve created a colorful animated background and made a clickable circle — now you’re building real interactivity!
💡 Bonus: Make a Simple “Click the Circle” Game
Let’s update the code to move the circle when it’s clicked — turning it into a simple game.
Update Your Script Like This:
canvas.addEventListener("click", function(event) {
let rect = canvas.getBoundingClientRect();
let mouseX = event.clientX - rect.left;
let mouseY = event.clientY - rect.top;
let dx = mouseX - circleX;
let dy = mouseY - circleY;
let distance = Math.sqrt(dx * dx + dy * dy);
if (distance < circleRadius) {
// Move circle to a random position
circleX = Math.random() * canvas.width;
circleY = Math.random() * canvas.height;
// Redraw everything
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
drawCircle();
}
});
// Initial draw
drawCircle();
Now every time you click the circle, it moves somewhere else — a fun little challenge!
💡 Bonus: Draw an Animated Logo
Let’s animate text fading in and out on the canvas.
Add This Below Your Gradient:
let opacity = 0;
let direction = 0.01;
function drawText() {
ctx.fillStyle = `rgba(255, 255, 255, ${opacity})`;
ctx.font = "bold 40px Arial";
ctx.fillText("Hello Canvas!", 150, 100);
}
function animateText() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
drawCircle(); // redraw the circle
drawText(); // draw animated text
// Update opacity
if (opacity >= 1 || opacity <= 0) {
direction *= -1; // reverse direction
}
opacity += direction;
requestAnimationFrame(animateText);
}
animateText(); // Start animation loop
Now your text fades in and out — adding motion to your canvas!

🧪 Try It Yourself!
- Replace the circle with a smiley face image and make it move when clicked.
- Use a radial gradient as a spotlight effect on the circle.
- Add multiple circles with different colors and track how many times each is clicked.
- Draw a smiley emoji that follows the mouse cursor around the canvas.
✅ Summary of What You Learned Today
CONCEPT | CODE EXAMPLE |
---|---|
Linear Gradient | ctx.createLinearGradient(x1, y1, x2, y2) |
Radial Gradient | ctx.createRadialGradient(x1, y1, r1, x2, y2, r2) |
Add Color Stop | gradient.addColorStop(position, color) |
Draw Image | ctx.drawImage(image, x, y, width, height) |
Detect Click | UsegetBoundingClientRect() and Pythagoras formula |
Animation Loop | UserequestAnimationFrame() |
🚀 Next Lecture Preview:
In Lecture 42 , we’ll learn about SVG (Scalable Vector Graphics) — another way to draw graphics on the web that scales perfectly and works well with CSS and JavaScript — ideal for icons, logos, and responsive designs!
Stay Updated
If you found this information useful, don’t forget to bookmark this page and Share.