info@tutsfinder.in



HTML Canvas



HTML Canvas element is the part of graphics which is used to draw a graphics on a web page.

The graphics which can be created usings canvas are like a red rectangle, a gradient rectangle, a multicolor rectangle, multicolor text etc.

HTML Canvas is used to draw graphics using Javascript.

The <canvas> tags works only as a container for graphics, for drawing the graphics javascript is used.

Canvas has several methods for drawing paths, boxes, circles, text etc.


Syntax:
<canvas id = “myCanvas” width =”100” height= “200”></canvas>

By default a canvas has no border and no content, if you want to add you can use style attribute.



Examples for HTML Canvas:

Draw a circle:
<!DOCTYPE html>
<html>
<body>

<canvas id="demo" width="200" height="100" style="border:1px solid #d3d3d3;"></canvas>

<script>
var x = document.getElementById("demo");
var ctx = x.getContext("2d");
ctx.beginPath();
ctx.arc(100,50,45,0,2*Math.PI);
ctx.stroke();
</script>

</body>
</html>


Output:

canvas

Draw Linear Gradient

Examples:
<!DOCTYPE html>
<html>
<body>

<canvas id="demo" width="200" height="130" style="border:1px solid #d3d3d3;"></canvas>

<script>
var x = document.getElementById("demo");
var ctx = x.getContext("2d");

var gradient = ctx.createLinearGradient(0,0,200,0);
gradient.addColorStop(0,"green");
gradient.addColorStop(1,"white");

ctx.fillStyle = gradient;
ctx.fillRect(20,20,150,80);
</script>

</body>
</html>


Output:

canvas

Stroke Text:



Examples:
<!DOCTYPE html>
<html>
<body>

<canvas id="demo" width="200" height="100" style="border:1px solid #d3d3d3;"></canvas>

<script>
var x = document.getElementById("demo");
var ctx = x.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Stroke Text",10,50);
</script>

</body>
</html>


Output:

canvas