HTML HTML Tutorial HTML Forms HTML Graphics HTML Media HTML APIs HTML Tags



HTML Canvas

HTML Canvas is a powerful tool for creating graphics and animations on the web. It allows developers to draw shapes, lines, text, and images on a web page using JavaScript. The canvas element is a rectangular area on a web page where you can draw graphics. It is a part of the HTML5 specification and is supported by all modern web browsers.

The canvas element is similar to an image tag, but instead of displaying an image, it displays a graphical representation of the code that you write. You can use the canvas element to create interactive games, data visualizations, and other dynamic content on your web page.

How to Use HTML Canvas

To use HTML Canvas, you need to create a canvas element in your HTML code. The canvas element has two attributes: width and height. These attributes determine the size of the canvas on the web page. You can set the width and height attributes to any value you want, but keep in mind that the larger the canvas, the more processing power it will require.

Once you have created the canvas element, you can use JavaScript to draw on it. The canvas element has a context object that you can use to draw shapes, lines, text, and images. The context object has a number of methods that you can use to draw on the canvas, such as fillRect(), strokeRect(), and fillText().

Code Examples

Here are some code examples that demonstrate how to use HTML Canvas:

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

<script>
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "red";
  ctx.fillRect(0, 0, 200, 200);
</script>

This code creates a canvas element with a width and height of 200 pixels. It then uses JavaScript to get the canvas element and its context object. It sets the fill style to red and draws a filled rectangle on the canvas.

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

<script>
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  ctx.beginPath();
  ctx.arc(100, 100, 50, 0, 2 * Math.PI);
  ctx.stroke();
</script>

This code creates a canvas element with a width and height of 200 pixels. It then uses JavaScript to get the canvas element and its context object. It begins a new path and draws a circle on the canvas using the arc() method. It then strokes the path to create an outline of the circle.

Conclusion

HTML Canvas is a powerful tool for creating graphics and animations on the web. It allows developers to draw shapes, lines, text, and images on a web page using JavaScript. The canvas element is a rectangular area on a web page where you can draw graphics. It is a part of the HTML5 specification and is supported by all modern web browsers.

References

Activity