Javatpoint Logo

91-9990449935

 0120-4256464

HTML Canvas Tag

The HTML canvas element provides HTML a bitmapped surface to work with. It is used to draw graphics on the web page.

The HTML 5 <canvas> tag is used to draw graphics using scripting language like JavaScript.

The <canvas> element is only a container for graphics, you must need a scripting language to draw the graphics. The <canvas> element allows for dynamic and scriptable rendering of 2D shapes and bitmap images.

It is a low level, procedural model that updates a bitmap and does not have a built-in scene. There are several methods in canvas to draw paths, boxes, circles, text and add images.

How to create a HTML canvas?

A canvas is a rectangle like area on an HTML page. It is specified with canvas element. By default, the <canvas> element has no border and no content, it is like a container.


HTML 5 Canvas Tag Example

Test it Now

Output:

Your browser does not support the HTML5 canvas tag.

Note: It is always necessary to specify the id attribute and the height & width attribute to define the size of the canvas. You can have multiple canvas elements on one HTML page.


Supporting Browsers

Elementchrome browser Chromeie browser IEfirefox browser Firefoxopera browser Operasafari browser Safari
<canvas>YesYesYesYesYes

HTML Canvas Tag with JavaScript

A canvas is a two dimensional grid.

Coordinates (0,0) defines the upper left corner of the canvas. The parameters (0,0,200,100) is used for fillRect() method. This parameter will fill the rectangle start with the upper-left corner (0,0) and draw a 200 * 100 rectangle.

Output:

Your browser does not support the HTML5 canvas tag.

Drawing Line on Canvas

If you want to draw a straight line on the canvas, you can use the following two methods.

moveTo(x,y): It is used to define the starting point of the line.

lineTo(x,y): It is used to define the ending point of the line.

If you draw a line which starting point is (0,0) and the end point is (200,100), use the stroke method to draw the line.

Output:

Your browser does not support the HTML5 canvas tag.

Drawing Circle on Canvas

If you want to draw a circle on the canvas, you can use the arc() method:

To sketch circle on HTML canvas, use one of the ink() methods, like stroke() or fill().

Output:

Your browser does not support the HTML5 canvas tag.

Drawing text on canvas

There are property and methods used for drawing text on the canvas.

font property: It is used to define the font property for the text.

fillText(text,x,y) method: It is used to draw filled text on the canvas. It looks like bold font.

strokeText(text,x,y) method: It is also used to draw text on the canvas, but the text is unfilled.

Let's see fillText() method example.

Output:

Sorry! Your browser does not support the HTML5 canvas tag.

Let's see strokeText() method example.

Output:

Sorry!Upgrade your browser. It does not support the HTML5 canvas tag.
Next TopicHTML SVG Tag