HTML CANVAS
The canvas is an element of HTML5 which is used to draw Graphics on the webpage.
The Graphics are created using javascript as scripting language.
Using canvas you can combine photos, create geometrical shapes, create animation, text etc.
The default size of canvas is 300px × 150px (height × width) but height and width can be changed using height/width attribute.
Basic canvas creation
Syntax:
<canvas id="your-id" height="value" width="value" ><canvas/>
since the default canvas created is blank and has no border. So to make canvas visible we can create a border.
<canvas id="canvas1" height="150" width="200" style="border: 1px solid gray"></canvas>
Try It
Output:
filling color in canvas
The canvas is by default white in color which can be given any color value.
To fill a color in a rectangle we use the function fillStyle = "color_name" .
To fill a rectangle we use the function fillRect ( left_padding, top_padding, width, height) .
<canvas id="canvas2" height="150" width="200" style="border: 1px solid gray">your browser do not support canvas.</canvas>
<script>
var canv = document.getElementById("canvas2");
var ctx = canv.getContext("2d");
ctx.fillStyle = "#006699";
ctx.fillRect(20, 30, 100, 100);
</script>
Try It
Output:
Drawing a line using canvas
To draw anything on canvas we have to use javascript.
First we need to select the target canvas we want to use by id value.
Then we define context for the canvas (2d or 3d) using getContext.
<canvas id="canvas3" height="150" width="200" style="border: 1px solid gray">your browser do not support canvas.</canvas>
<script>
var canv = document.getElementById("canvas2");
var ctx = canv.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 150);
ctx.stroke();
</script>
Try It
Output:
Drawing a circle on canvas
To draw a circle on canvas we use arc() method.
The arc() method takes five arguments: arc( x, y, r, start, stop).
<canvas id="canvas4" height="150" width="200" style="border: 1px solid gray">your browser do not support canvas.</canvas>
<script>
var canv = document.getElementById("canvas4");
var ctx = canv.getContext("2d");
ctx.beginPath();
ctx.arc(50, 50, 35, 0, 2 * Math.PI);
ctx.stroke();
</script>
Try It
Output: