html
  1. html-canvas

HTML Canvas

The <canvas> element is used to draw graphics on a web page. It has two attributes: width and height, which define the dimensions of the canvas.

Syntax

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

Example

To draw on the canvas, you need to use JavaScript.

Here's a simple example of drawing a blue rectangle on the canvas:

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

<script>
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "blue";
  ctx.fillRect(10, 10, 150, 80);
</script>
Try Playground

Explanation

  • The getContext("2d") method is used to get a 2D drawing context for the canvas.
  • fillStyle is set to "blue" to define the fill color.
  • fillRect(x, y, width, height) is used to draw a filled rectangle.

Use

The HTML canvas element is commonly used for dynamic rendering, animations, and interactive graphics on web pages.

Important Points

The canvas is initially transparent. Anything drawn on it will cover existing content. The canvas fallback content (what's displayed when the browser doesn't support canvas) can be placed inside the <canvas> element.

Summary

In summary, the HTML canvas is a powerful element for creating dynamic graphics and visualizations on the web. By combining it with JavaScript, you can draw various shapes, images, and patterns, making it a versatile tool for web developers.

Published on: