in HTML 5

Draw a circle with Canvas

What is canvas?

The HTML5 canvas element is used to draw graphics, on the fly, using javascript. This can be used to draw graphs, make photo composition or animations. It is only a container for graphics and it has several methods for drawing paths, boxes, circles, text, and adding images.

Create Canvas Element

<canvas id="myCanvas">
Your browser does not support the HTML5 canvas tag.
</canvas>

It is similar to div element, rectangular area on an HTML page. By default, canvas will not have any css properties unless we are not giving. We can style canvas element, the similar way we style a div. We have to use width and height for the element as per the requirement. It is always better to use ‘id’ for the canvas element, so that it can be easily identified.

Add the text as given in the code, it is fallback content, so that if the browser does not support this element, the given message will be displayed.

CSS

#myCanvas {
   width: 400px;
   height: 400px;
   border: 1px solid #c5c5c5c;
}

How to Draw a circle onto the Canvas?

The following is the script for drawing a circle.

    <script type="text/javascript">
 var c=document.getElementById("myCanvas");
 var ctx=c.getContext("2d");
 ctx.beginPath();
 ctx.arc(95,50,40,0,2*Math.PI);
 ctx.stroke();
 </script>

document.getElementById() retrieves the canvas element with the id myCanvas.
Then, we are getting the context of the canvas (2d) and storing it in ‘ctx’ variable. The getContext() method returns an object that provides methods and properties for drawing on the canvas element. Canvas element creates a fixed-size drawing surface that exposes one or more rendering contexts, which are used to create and manipulate the content shown. Here, we are using the arc() method for drawing a circle and adding the parameters. When we use this method arc(x,y,r,start,stop), x and y cordinates should be given at first, then the radius (r), then start and end position.

Demo



Your browser does not support the HTML5 canvas tag.

Related Posts

Written By:

Add a Comment

Your email address will not be published. Required fields are marked *