The HTML Canvas tag <canvas> is used to draw graphics on your web page using javascript. It works as a container for your graphics. We can draw actual graphics using javascript. We can draw various drawings like boxes, circles, text, images, etc. There are two main attributes of the <canvas> tag Height and Width.
<script> var c = document.getElementById("circle"); var cx = c.getContext("2d"); cx.beginPath(); cx.arc(100, 100, 70, 0, 3 * Math.PI); cx.stroke(); </script>
</body>
</html>
Output:
Canvas tag can also be used to draw text on the web page. There are various properties and methods defined to draw text. Some properties are font property, fillTextmethod, strokeText method, etc.
Font Property
It defines the font property of the text
fillText(text, x, y)
It draws filled text on the canvas.
strokeText(text,x,y)
It draws unfilled text on the canvas.
<canvasid="text"width="350"height="100"
style="border:1px solid #d3d3d3;">
</canvas> <script>
var c = document.getElementById("text"); var ctx = c.getContext("2d"); ctx.font = "20px Arial"; ctx.fillText("This is a Demo", 20, 60); </script>
Output:
Here, we have used the fillTextmethod.
You can also draw lines on the canvas. There are two methods you can use to do so :
moveTo(x,y)
This property defines the starting point of the line.
lineTo(x,y)
This property defines the ending point of the line.
The below example shows how to draw a straight line :