
One of the most powerful features offered by HTML5 is the <canvas>
tag. This tag allows us to draw graphics, shapes, and animations using JavaScript. It's especially useful for game development, data visualization, and interactive web projects.
Using the Canvas
To start drawing, we first need to create a <canvas>
element.
<canvas id='drawingArea' width='500' height='300' style='border:1px solid #000;'></canvas>
Drawing a Basic Shape
Now let's draw a rectangle on the canvas using JavaScript:
<script>
var canvas = document.getElementById('drawingArea');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 200, 100);
</script>
This code draws a blue rectangle at position (50, 50) with a width of 200 and height of 100.
Drawing a Line and a Circle
ctx.beginPath();
ctx.moveTo(50, 200);
ctx.lineTo(250, 200);
ctx.strokeStyle = 'red';
ctx.lineWidth = 5;
ctx.stroke();
ctx.beginPath();
ctx.arc(350, 150, 50, 0, Math.PI * 2);
ctx.fillStyle = 'green';
ctx.fill();
This code draws a red line and a green circle.
HTML5 Canvas is a powerful tool for creating graphics and animations on the web. When combined with JavaScript, it enables the development of advanced interactive applications. Starting with basic shapes, it can be used for everything from animations to full-scale game designs.
Related Articles
