For working professionals
For fresh graduates
More
Learn HTML: A Comprehensive Tu…
1. HTML Tutorial
2. HTML Basics
3. HTML Syntax
4. HTML Elements
5. HTML Attributes
6. HTML Comments
7. HTML Semantic
8. HTML Form Elements
9. HTML Head
10. HTML Title
11. HTML Styles
12. HTML Paragraphs
13. HTML Symbols
14. HTML Emojis
15. HTML Formatting
16. HTML Entities
17. HTML Audio
18. HTML Images
19. HTML Lists
20. HTML Links
21. SVG in HTML
22. HTML Forms
23. HTML Video
24. HTML Canvas
Now Reading
25. Adjacency Lists
26. HTML Input Types
27. HTML Tables
28. HTML Table Border
29. Cell Spacing and Cell Padding
30. HTML Semantic Elements
31. HTML Layout
32. html blocks and inline
33. HTML Div
34. Difference Between HTML and CSS
35. Image Map in HTML
36. HTML Drag and Drop
37. HTML Iframes
38. Divide and Conquer Algorithm
39. Difference Between HTML and XHTML
40. HTML Code
41. HTML Colors
42. HTML CSS
43. HTML Editors
44. HTML Examples
45. Class in HTML
46. HTML Exercises
47. HTML ID
48. Understanding HTML Encoding: A Comprehensive Guide
49. HTML Table Style
50. HTML Script
51. Introduction to HTML
Imagine having a virtual drawing board right in your web browser where you can create incredible artwork, animations, and interactive games. That is exactly what HTML canvas aims to be! It's similar to a magical canvas where developers may use code to sketch, paint, animate, and bring creative ideas to life on a website.
In this HTML canvas tutorial, I will explore how HTML canvas works. I'll guide you on how to use this tool to draw shapes, add colors, produce animations, and develop interactive features.
Canvas is an HTML element that allows developers to dynamically create visuals, animations, and interactive content using JavaScript. It enables developers to create shapes, lines, text, photos, and other elements directly within a web browser.
The element serves as a blank canvas for canvas HTML5 JavaScript to modify pixels and build visual elements, making it an effective tool for developing games, data visualizations, interactive charts, animations, and unique user interfaces for the web. We use the canvas tag in HTML to define this element. Let me show you an example to give you a better understanding.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> HTML Canvas Example </title>
</head>
<body>
<canvas id="myCanvas_example" width="200" height="100"></canvas>
<script>
// Get the canvas element which is myCanvas_example
var canvas = document.getElementById("myCanvas_example");
// Get the drawing context which is 2D
var ctx = canvas.getContext("2d");
// Drawing a rectangle
ctx.fillStyle = "#FF8213"; // Orange color
ctx.fillRect(10, 10, 150, 80); // x, y, width, height
</script>
</body>
</html>
Now, let me dissect the above example to explain the program better.
Let us now discuss different use cases of canvas using different examples one by one.
First, let me start with how to draw a line in HTML canvas. I’ll explain with an example.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Canvas Line Example</title>
<style>
#myCanvas_line{
border: 2px solid red;
}
</style>
</head>
<body>
<canvas id="myCanvas_line" width="400" height="200"></canvas>
<script>
// Get the canvas element which is myCanvas_line
var canvas = document.getElementById("myCanvas_line");
// Get the drawing context (2D)
var ctx = canvas.getContext("2d");
// Set line style
ctx.strokeStyle = "#AA00FF"; // Purple color
ctx.lineWidth = 7; // 7 pixels wide
// Draw a line
ctx.beginPath();
ctx.moveTo(50, 50); // Starting point (x, y)
ctx.lineTo(350, 150); // Ending point (x, y)
ctx.stroke(); // Draw the line
</script>
</body>
</html>
Now, let me explain the above example.
When you open this HTML file in a web browser, a purple line will appear on the canvas between points (50, 50) and (350, 150), as you can see in the above example.
Now let me teach you how to add text using canvas in HTML with the help of an example.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Canvas Text Example</title>
<style>
#myCanvas_text{
border: 2px solid blue;
}
</style>
</head>
<body>
<canvas id="myCanvas_text" width="500" height="300"></canvas>
<script>
// Get the canvas element which is myCanvas_text
var canvas = document.getElementById("myCanvas_text");
// Get the drawing context (2D)
var ctx = canvas.getContext("2d");
// Set text style
ctx.font = "30px Arial"; // Font size and type
ctx.fillStyle = "#AA0000"; // Text color assigned to red
// Write text you want to show
ctx.fillText("HTML Canvas Text!", 150, 200); // Text, x, y
</script>
</body>
</html>
Let’s dissect the above example.
As you can see in the output, the text "HTML Canvas Text!" will appear in red at the specified coordinates on the canvas. You can customize the font size, font type, text color, and position to the needs of the website you are creating.
We can also apply a gradient effect to our canvas to make it more interesting. Let me demonstrate this with an example.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Example of HTML Canvas Gradient </title>
<style>
#myCanvas_gradient{
border: 2px solid red;
}
</style>
</head>
<body>
<canvas id="myCanvas_gradient" width="500" height="300"></canvas>
<script>
// Get the canvas element
var canvas = document.getElementById("myCanvas_gradient");
// Get the drawing context (2D)
var ctx = canvas.getContext("2d");
// Here we are Creating a linear gradient
var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop(0, "lightgreen"); // Start color is lightgreen
gradient.addColorStop(1, "blue"); // End color is blue
// Here we are Filling the rectangle with gradient
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
</script>
</body>
</html>
Let me explain the above program point by point.
When you use this example program on your own, you'll notice a horizontal gradient from light green to blue filling the canvas. Always remember, this is just an example and you can tweak all the properties as per your liking and needs of your program. You can further refine your skills by practicing different HTML projects.
Now, let me teach you how to draw a circle with the help of canvas in HTML.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Example of HTML Canvas Circle </title>
<style>
#myCanvas_circle{
border: 2px solid blue;
}
</style>
</head>
<body>
<canvas id="myCanvas_circle" width="500" height="300"></canvas>
<script>
// Get the canvas element which is myCanvas_circle in this program
var canvas = document.getElementById("myCanvas_circle");
// Get the drawing context (2D)
var ctx = canvas.getContext("2d");
// Setting up the circle properties
var centerX = canvas.width / 2; // X-coordinate of circle center
var centerY = canvas.height / 2; // Y-coordinate of circle center
var radius = 60; // Circle radius
var startAngle = 0; // Start angle (in radians)
var endAngle = 2 * Math.PI; // End angle (in radians)
var anticlockwise = false; // Direction of drawing (clockwise or anticlockwise)
// Draw circle
ctx.beginPath(); // Begin drawing path of the circle
ctx.arc(centerX, centerY, radius, startAngle, endAngle, anticlockwise); // Draw arc of the circle
ctx.fillStyle = "lightgreen"; // Circle fill color set to light green
ctx.fill(); // Fill circle with color
ctx.closePath(); // Close drawing path
</script>
</body>
</html>
Let’s explain the above example.
If you run this program, you will see a circle that is light green in color. You can change the attributes as per your wants.
HTML Canvas is an effective tool for producing dynamic and interactive graphics on websites. From simple shapes and animations to complex graphics and game creation, the Canvas API opens up new creative possibilities for web developers and designers.
If you want to learn more about HTML elements, I would recommend checking out courses from upGrad. They offer some of the best-certified courses available in the industry.
The canvas element in HTML dynamically draws graphics, animations, and interactive information on a webpage using JavaScript. It provides a drawing surface that enables developers to create and manipulate graphical components, including lines, forms, text, images, and animations right in the browser.
Canvas is supported by almost all modern browsers, with the exception of a few very outdated versions.
You can add CSS with canvas to style the container and add animations but you cannot use CSS to change the shapes and graphics in the canvas itself.
Canvas in HTML is an excellent choice for complex visuals, especially if you require fine-grained control, animation, and performance. However, the development process might be quite difficult.
Numerous tools and frameworks are available to make working with Canvas easier, particularly for complex visuals. Some of them include Three.js for 3D models and Anime.js for animation.
In canvas, a path is a set of connected points that describe the shape you want to draw on the canvas. It's like a blueprint for your drawing. Paths are created using JavaScript techniques provided by the Canvas API.
Canvas is primarily for 2D graphics. It offers a useful API for drawing shapes, lines, text, and images on a webpage. While the canvas API does not directly create actual 3D visuals, there are techniques to achieve some 3D-like effects.
Canvas in HTML has various restrictions that make it unsuitable for producing high-quality printable graphics because of limited vector support and resolution dependence.
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.