Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use the HTML 5 Canvas tag?

Forgive me my ignorance but I am very new to the HTML 5 arena and never worked with graphics using Javascript.

I was doing some reading and came across the Canvas tag and the source stated that the canvas tag acts as a graphics container and is used to render graphics on the webpage by the use of Javascript.

My questions is, why would I need to use Canvas as a placeholder to render graphics instead of using some other arbitrary tag that can be used as a graphics placeholder for example?

like image 811
Draco Avatar asked Sep 09 '11 13:09

Draco


People also ask

What is the purpose of canvas in HTML5?

The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript. The <canvas> element is only a container for graphics. You must use JavaScript to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

Why do we use canvas tag?

The <canvas> tag is used to draw graphics, on the fly, via scripting (usually JavaScript). The <canvas> tag is transparent, and is only a container for graphics, you must use a script to actually draw the graphics.

Is HTML5 canvas still used?

The HTML5 canvas has the potential to become a staple of the web, enjoying ubiquitous browser and platform support in addition to widespread webpage support, as nearly 90% of websites have ported to HTML5.


2 Answers

A <canvas> tag is exactly like an <img> tag, with the difference that instead of loading the image from the network you can draw it yourself with javascript code. You can draw lines, circles, filled polygons, gradients and matrix-transformed pictures. You can also redraw the canvas content in a loop to make an animation.

To see what you can do with a plain canvas 2d (no webgl, just standard 2d rendering) take a look at this small demo or look at this video if your browser is too old and doesn't support canvas.

It's pure javascript, nothing loaded from the network, everything is computed in the browser, including the texture and the raytraced image used for envmapping part. All in a single 4Kb html file.

Do you really think you can do the same using regular <div>s ?

EDIT:

For a much simpler demo with a readable source you can check out this rotating icosahedron.

like image 112
6502 Avatar answered Oct 23 '22 09:10

6502


Canvas is intended for graphics manipulation, whereas div isn't. Semantically, you should be using Canvas.

like image 23
Oded Avatar answered Oct 23 '22 10:10

Oded