官术网_书友最值得收藏!

Drawing a circle

Although the HTML5 canvas API doesn't support a circle method, we can certainly create one by drawing a fully enclosed arc.

Drawing a circle

How to do it...

Follow these steps to draw a circle centered on the canvas:

  1. Define a 2D canvas context:
    window.onload = function(){
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
  2. Create a circle using the arc() method, set the color fill using the fillStyle property, and then fill the shape with the fill() method:
        context.arc(canvas.width / 2, canvas.height / 2, 70, 0, 2 * Math.PI, false);
        context.fillStyle = "#8ED6FF";
        context.fill();
        context.lineWidth = 5;
        context.strokeStyle = "black";
        context.stroke();
    };
  3. Embed the canvas tag inside the body of the HTML document:
    <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
    </canvas>

How it works...

As you might recall from Chapter 1, we can create an arc using the arc() method which draws a section of a circle defined by a starting angle and an ending angle. If, however, we define the difference between the starting angle and ending angle as 360 degrees (2π), we will have effectively drawn a complete circle:

context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

See also...

  • Creating patterns with loops: drawing a gear
  • Transforming a circle into an oval in Chapter 4
  • Swinging a pendulum in Chapter 5
  • Simulating particle physics in Chapter 5
  • Animating a clock in Chapter 5
  • Detecting region events in Chapter 6
  • Creating a pie chart in Chapter 7
主站蜘蛛池模板: 德庆县| 扬中市| 从江县| 延寿县| 祁阳县| 贡觉县| 宁海县| 汨罗市| 庆阳市| 佛山市| 海晏县| 四平市| 嘉善县| 莲花县| 陆河县| 宜兰市| 西藏| 鄂托克前旗| 犍为县| 丹江口市| 韶山市| 新密市| 宁德市| 新津县| 阳山县| 台中市| 长宁区| 乌拉特后旗| 额尔古纳市| 尼木县| 金昌市| 天全县| 淮北市| 天水市| 紫云| 海安县| 枣强县| 云龙县| 嵊泗县| 东乡族自治县| 镇远县|