HTML5 Canvas

HTML5 canvas element is used to draw graphics, animation, dynamic images, diagram, text to enhance the user experience.

<canvas> tag is used to add canvas on the web page. It is pixel based and powered by javascipt. The canvas area of the web page is accessed by javascript code. So canvas is fully interactive. It responds to user actions like touch, mouse click etc. You should have good knowledge of javascript for this. Canvas provides features to draw and manipulate images in any 2D and 3D context. We can draw both static and dynamic graphics and animation. These days HTML5 canvas is an ideal api in gaming.

Canvas Element

Canvas is a rectangle area with by default 300px width and 150px height. We can change this according to our requirement. This is the way to include a canvas element to the web page.

<canvas width="250" height="150"></canvas>

The above tag shows nothing on the webpage. By default canvas is transparent and it has no border and text. To represent our drawing, we need javascript, like this.

Canvas Example

<canvas id="cnvs" width="250" height="150" style="border:1px solid #000000;">
</canvas>
<script>
var canvas = document.getElementById('cnvs');
var ctx = canvas.getContext("2d");
ctx.fillStyle = 'yellow'; 
ctx.fillRect(20, 20, 100, 100);
</script>

Output of the above code

In the above example, getContext is a method that returns an object for working on canvas. fillStyle is a property of canvas and used to fill color gradient in the drawing and fillRect method is used to draw a filled rectangle.







Read more articles


General Knowledge



Learn Popular Language