Drawing circles with JavaScript and HTML5 Canvas

The HTML5 specification includes the canvas element for drawing graphics with JavaScript. This example demonstrates the use of the canvas element and JavaScript for drawing circles.

<!DOCTYPE html>
<html>
<head>
    <title>Circles with JavaScript and HTML5 Canvas</title>

    <script type="text/javascript">
        var padding = 200;

        // Draws a circle with a given radius
        function drawCircleCustom(radius){
            var drawingCanvas = document.getElementById('drawingCanvas');
            var drawingContext = drawingCanvas.getContext('2d');
            var degrees = 360;

            // Construct the path of the circle
            drawingContext.beginPath();

            for(var i=1;i<=degrees;i++){
                var X = Math.cos(i)*radius;
                var Y = Math.sin(i)*radius;
                var Xto = Math.cos(i+0.1)*radius;
                var Yto = Math.sin(i+0.1)*radius;

                drawingContext.moveTo(X+padding,Y+padding);
                drawingContext.lineTo(Xto+padding,Yto+padding);
            }

            drawingContext.closePath();

            // Draw the path
            drawingContext.stroke();

        }

        // Draws a circle with a given radius
        function drawCircleRegular(radius){
            var drawingCanvas = document.getElementById('drawingCanvas');
            var drawingContext = drawingCanvas.getContext('2d');
            drawingContext.beginPath();
            drawingContext.arc(150, 150, radius, Math.PI*2, 0, true);
            drawingContext.closePath();

            drawingContext.stroke();
        }

    </script>

</head>

<body onload="drawCircleCustom(100);drawCircleRegular(100);">

<canvas id="drawingCanvas" width="500" height="500">
  Why don't you get a real browser?   <!-- Displayed if the client does not support HTML5 -->
</canvas>

</body>
</html>

Result:

Circles

 

 

This entry was posted in JavaScript and tagged , , , , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

3 Comments

  1. Steven Horton
    Posted September 3, 2011 at 1:12 am | Permalink

    The anti-bot question down here is ridiculous. XD

    • Posted September 3, 2011 at 8:17 am | Permalink

      lol :) Haven’t had spam in ages !!

  2. Vitaly
    Posted May 29, 2013 at 12:59 pm | Permalink

    That’s a very interesting way to generate irrelevant comments.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?