In HTML5, the <canvas>
element is used to draw graphics using JavaScript. It provides a drawing surface that you can use to create dynamic and interactive content such as charts, animations, games, and more. Here's a basic overview of how to use the <canvas>
element:
Create a Canvas Element:
Add the <canvas>
element to your HTML document. You can specify the width and height attributes to set the size of the canvas.
html<canvas id="myCanvas" width="500" height="300"></canvas>
Get the Canvas Context: To draw on the canvas, you need to get the drawing context. This is done using JavaScript.
html<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
</script>
Here, context
is an object that provides methods for drawing on the canvas.
Draw on the Canvas: Once you have the context, you can use its methods to draw shapes, text, images, and more. Here are some examples:
Drawing a Rectangle:
html<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// Draw a filled rectangle
context.fillStyle = 'blue';
context.fillRect(50, 50, 100, 80);
</script>
Drawing a Circle:
html<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// Draw a circle
context.beginPath();
context.arc(150, 150, 50, 0, 2 * Math.PI);
context.fillStyle = 'red';
context.fill();
context.stroke();
</script>
Drawing Text:
html<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// Draw text
context.font = '20px Arial';
context.fillStyle = 'green';
context.fillText('Hello, Canvas!', 50, 200);
</script>
These are just simple examples, and the <canvas>
element provides many more features for creating complex graphics and animations. You can explore the various drawing methods and properties of the 2D rendering context to achieve the desired visual effects. Additionally, you can use JavaScript events to create interactive applications on the canvas.