The HTML canvas tag draws shapes and images. It also helps you draw text with code. It gives control over 2D graphics and animations with real-time updates.
Table of Content
Understand the <canvas> Tag in HTML
The <canvas> tag creates a drawing space inside a web page. You use JavaScript to draw shapes or lines. Also, images or text inside it. The <canvas> tag itself is blank.
The syntax looks like this:
<canvas id="myCanvas" width="300" height="150"></canvas>
- id lets you target the canvas with JavaScript.
- width and height set the size of the canvas in pixels.
- If you skip size, it defaults to 300Ć150 pixels.
How to Use JavaScript with the <canvas> Tag
JavaScript must select the canvas and use its getContext() method.
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
- ctx now controls the canvas.
- “2d” means you use the 2D drawing mode.
Draw Shapes with <canvas>
Tag in HTML
Here you have to use methods on the ctx
object:
Draw a Line:
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(200, 100);
ctx.stroke();
Here is how it works:
- beginPath() starts a new line.
- moveTo(x, y) sets the start point.
- lineTo(x, y) sets the end point.
- stroke() draws the line.
Here is how to draw a rectangle:
ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 100, 80);
- fillStyle sets the color.
- fillRect(x, y, width, height) draws a filled box.
This code shows you how to draw a Circle:
ctx.beginPath();
ctx.arc(150, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = "green";
ctx.fill();
- arc(x, y, radius, startAngle, endAngle) defines the circle.
- Use Math.PI to set angle values.
- fill() paints the circle.
Here are more 2D drawing function examples:
Draw text:
ctx.font = "20px Arial";
ctx.fillStyle = "black";
ctx.fillText("Hello Canvas", 100, 50);
Clear canvas:
ctx.clearRect(0, 0, canvas.width, canvas.height);
Image Manipulation with <canvas> Tag in HTML
You can draw an image and edit its pixels. This works in real-time.
const img = new Image();
img.onload = function () {
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const pixels = imageData.data;
for (let i = 0; i < pixels.length; i += 4) {
pixels[i] = 255 - pixels[i];
pixels[i + 1] = 255 - pixels[i + 1];
pixels[i + 2] = 255 - pixels[i + 2];
}
ctx.putImageData(imageData, 0, 0);
};
img.src = "photo.jpg";
This code loads an image and shows it on a canvas. It reads all the pixels (tiny dots of color) from the canvas once the image loads.
It changes each pixelās color to its opposite by subtracting its red, green, and blue values from 255.
This creates an “inverted” or “negative” effect and puts the updated image back on the canvas so you can see the result.
Animations with the <canvas> Tag in HTML
Use requestAnimationFrame() for smooth results.
let x = 0;
function drawFrame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, 75, 20, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
x += 2;
requestAnimationFrame(drawFrame);
}
drawFrame();
This code makes a red circle move across the canvas from left to right. It starts by setting x
to 0, which is the circleās starting point.
The drawFrame
function clears the canvas, draws a red circle at position x
, then increases x
by 2 to move the circle to the right.
The requestAnimationFrame(drawFrame)
keeps calling the function again and again to create a smooth animation.
Handle Event on <canvas> Tag in HTML
Canvas does not have built-in events for clicks or keys. Use JavaScript to track events.
Mouse and Keyboard Interactions on Canvas Elements:
canvas.addEventListener("click", function (event) {
const x = event.offsetX;
const y = event.offsetY;
ctx.fillStyle = "blue";
ctx.fillRect(x - 5, y - 5, 10, 10);
});
Keyboard events work on the full page:
document.addEventListener("keydown", function (event) {
if (event.key === "ArrowRight") {
console.log("Move right");
}
});
Canvas vs SVG for Graphics Rendering
Canvas draws pixels. It does not remember shapes. The SVG draws vector shapes in the DOM. Each shape stays editable.
Here are the key differences:
Feature | Canvas | SVG |
---|---|---|
Shape storage | No | Yes |
Performance | Faster for many shapes | Slower with many shapes |
Interactions | Manual | Built-in |
Resize support | Needs redraw | Auto-scale |
Use cases:
- Use for games or image editing with real-time updates.
- Use SVG for charts or maps with static graphics.
Browser Support and Compatibility
The <canvas> tag works in all modern browsers.
Browser | Support |
Chrome | Yes |
Firefox | Yes |
Safari | Yes |
Edge | Yes |
Opera | Yes |
Examples
Draw a Grid of Squares:
const size = 20;
for (let y = 0; y < canvas.height; y += size) {
for (let x = 0; x < canvas.width; x += size) {
ctx.strokeRect(x, y, size, size);
}
}
This draws a grid over the canvas using strokeRect() in two loops.
Animate a Bouncing Ball:
let x = 100;
let y = 100;
let dx = 3;
let dy = 2;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, y, 10, 0, 2 * Math.PI);
ctx.fill();
x += dx;
y += dy;
if (x < 10 || x > canvas.width - 10) dx = -dx;
if (y < 10 || y > canvas.height - 10) dy = -dy;
requestAnimationFrame(animate);
}
animate();
This animates a ball that bounces off the canvas edge.
Draw with the Mouse:
let draw = false;
canvas.addEventListener("mousedown", () => draw = true);
canvas.addEventListener("mouseup", () => draw = false);
canvas.addEventListener("mousemove", function (event) {
if (!draw) return;
const x = event.offsetX;
const y = event.offsetY;
ctx.fillRect(x, y, 4, 4);
});
This lets you paint on the canvas using the mouse.
Wrapping Up
In this article, you learned how the <canvas> tag works, how to draw shapes or images, and how to animate with JavaScript. Also, you learned how to track mouse and keyboard events.
Here is a quick recap:
- draws with JavaScript code
- You can draw any shape
- You can add image filters and real-time updates
- You can animate frames and add interactions
- Canvas is different from SVG in behavior and performance
FAQs
What is the use of the <canvas> tag in HTML5?
The <canvas> tag in HTML5 is used to draw graphics on a web page via JavaScript. It allows developers to render shapes, images, text, and even animations on the fly. Unlike SVG, <canvas> is bitmap-based and is ideal for game development, image editing, or dynamic visual content.
<canvas id="myCanvas" width="300" height="150"></canvas>
You can then draw on it using JavaScript:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 100, 50);
How do you draw shapes using the <canvas> tag and JavaScript?
To draw shapes using the <canvas> element, you need to access its rendering context with JavaScript, usually using getContext("2d")
. Then, use drawing methods like fillRect
, strokeRect
, or arc
for circles.
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Draw rectangle
ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 150, 100);
// Draw circle
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();
What is the difference between <canvas> and SVG in HTML?
Both <canvas> and SVG are used to draw graphics, but they have key differences:
- <canvas>: Bitmap-based, ideal for dynamic graphics, games, and real-time rendering.
- SVG: Vector-based, better for static graphics, icons, and charts where accessibility is important.
Example of <canvas>:
<canvas id="drawArea" width="200" height="100"></canvas>
How to animate using the <canvas> tag in JavaScript?
You can create animations in <canvas> using the requestAnimationFrame()
method. This allows you to update your canvas graphics smoothly in a loop.
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, 75, 20, 0, Math.PI * 2);
ctx.fillStyle = "green";
ctx.fill();
x += 2;
requestAnimationFrame(animate);
}
animate();
Similar Reads
The nav tag defines a navigation block in HTML. It holds main links to other parts of your site. Search…
The <code> tag in HTML shows short code, command names, or output. Use it to display text that the browser…
Forms need instructions so users know what to enter. You use the HTML label tag to give names to input…
The HTML em tag shows stress or emphasis in text. It changes meaning for readers and screen readers. What is…
The <dialog> tag is used to build modal popups in HTML. It shows alerts and messages without third-party scripts. Understand…
The HTML lang attribute tells browsers and tools what language the page uses. It helps users and search engines understand…
You need images to show products or ideas on your site. The HTML img tag places those images on the…
The data tag connects visible content with a machine-readable value in HTML. This helps browsers and tools understand and process…
The link tag in HTML connects a web page to external resources like stylesheets or icons. It's placed in the…
HTML global attributes work on most elements. They do not depend on the tag name. You can use them with…