- HTML5 Canvas Cookbook
- Eric Rowell
- 233字
- 2021-08-27 12:08:06
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.

How to do it...
Follow these steps to draw a circle centered on the canvas:
- Define a 2D canvas context:
window.onload = function(){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d");
- Create a circle using the
arc()
method, set the color fill using thefillStyle
property, and then fill the shape with thefill()
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(); };
- 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);