Skip to main content

HTML <canvas> Tag

The HTML <canvas> element is a container for graphics that can be rendered on the fly using JavaScript. It is commonly used to create dynamic, interactive graphics for web applications, such as games, data visualizations, and image editing tools.

To use the <canvas> element, you need to include it in your HTML code like any other element:

<canvas id="myCanvas" width="600" height="240"></canvas>

The id attribute is optional, but it is a good idea to include it if you plan on manipulating the canvas with JavaScript. The width and height attributes define the size of the canvas in pixels.

Once you have added the <canvas> element to your HTML, you can use JavaScript to draw graphics on it. The <canvas> element provides a number of methods for drawing shapes, lines, and text, as well as loading and displaying images.

Here is an example of how to draw a simple line on a canvas:

<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.moveTo(0, 0);
context.lineTo(100, 100);
context.stroke();
</script>

This code uses the getContext method of the canvas element to get a 2d context, which provides the methods for drawing on the canvas. The moveTo and lineTo methods define the start and end points of the line and the stroke method draws it.

You can also use the <canvas> element to display images. Here is an example of how to load and display an image on a canvas:

<canvas id="myCanvas" width="500" height="300"></canvas>
<script> var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var image = new Image();
image.onload = function() { context.drawImage(image, 0, 0); }
image.src = 'path/to/image.jpg';
</script>

This code creates a new image object and sets the src attribute to the path of the image file. The onload event handler is called when the image has finished loading, at which point the drawImage method is used to draw the image on the canvas.

There are many other methods and techniques for drawing and manipulating graphics on a canvas, such as drawing shapes, applying transformations, and using gradients and patterns. The <canvas> element is a powerful tool for creating dynamic, interactive graphics for web applications, and is widely used by web developers.