HTML Canvas

Canvas in HTML

The <canvas> element is used to draw graphics on a web page via JavaScript. It is a blank rectangular area where you can draw shapes, text, images, and other objects.

Creating a Canvas

To create a canvas, you use the <canvas> tag in HTML. You can specify the width and height of the canvas. If these attributes are not specified, the default size is 300 pixels wide and 150 pixels high.

<canvas id="myCanvas" width="400" height="200"></canvas>
            

Getting the Canvas Context

To draw on the canvas, you need to get the 2D rendering context from the canvas element. This is done using the getContext() method. Here is an example of how to do it:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
            

Drawing Shapes

Once you have the rendering context, you can start drawing shapes. Here’s how to draw a rectangle:

ctx.fillStyle = "blue"; // Set the fill color
ctx.fillRect(20, 20, 150, 100); // Draw a filled rectangle
            

Drawing a Circle

To draw a circle, you use the arc() method:

ctx.beginPath(); // Start a new path
ctx.arc(240, 70, 50, 0, Math.PI * 2); // Draw a circle
ctx.fillStyle = "red"; // Set the fill color
ctx.fill(); // Fill the circle
            

Drawing Text

You can also draw text on the canvas using the fillText() method:

ctx.font = "30px Arial"; // Set the font size and family
ctx.fillStyle = "green"; // Set the text color
ctx.fillText("Hello, Canvas!", 50, 150); // Draw the text
            

Canvas Example

Here is a complete example that puts all the above pieces together:

<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

// Draw a rectangle
ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 150, 100);

// Draw a circle
ctx.beginPath();
ctx.arc(240, 70, 50, 0, Math.PI * 2);
ctx.fillStyle = "red";
ctx.fill();

// Draw text
ctx.font = "30px Arial";
ctx.fillStyle = "green";
ctx.fillText("Hello, Canvas!", 50, 150);
</script>
            

Conclusion

The canvas element provides a powerful and flexible way to draw graphics and animations on a web page. By using JavaScript, you can create dynamic graphics that can respond to user interactions.