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

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
主站蜘蛛池模板: 虎林市| 东乡县| 桃园市| 光泽县| 从化市| 临桂县| 南漳县| 娄底市| 启东市| 兴宁市| 华容县| 灌云县| 新和县| 阿瓦提县| 堆龙德庆县| 汽车| 临猗县| 温宿县| 宜丰县| 林芝县| 铁岭市| 长宁县| 新沂市| 平阳县| 邻水| 怀柔区| 历史| 贵港市| 凤翔县| 界首市| 连南| 万安县| 松潘县| 娱乐| 九台市| 嘉荫县| 锡林浩特市| 宜君县| 新郑市| 陆良县| 丽江市|