Javascript Draw Circle on Canvas
Drawing shapes with canvas
- « Previous
- Next »
At present that we accept ready our canvass environs, we can get into the details of how to draw on the canvas. By the end of this article, you will have learned how to draw rectangles, triangles, lines, arcs and curves, providing familiarity with some of the basic shapes. Working with paths is essential when drawing objects onto the sail and we will meet how that can be washed.
The filigree
Earlier we tin start drawing, we demand to talk virtually the canvas grid or coordinate space. Our HTML skeleton from the previous page had a sheet chemical element 150 pixels wide and 150 pixels high.
Ordinarily 1 unit in the grid corresponds to 1 pixel on the canvas. The origin of this grid is positioned in the height left corner at coordinate (0,0). All elements are placed relative to this origin. And so the position of the top left corner of the blueish square becomes x pixels from the left and y pixels from the top, at coordinate (x,y). Later on in this tutorial we'll run into how nosotros can translate the origin to a different position, rotate the grid and fifty-fifty scale it, only for now we'll stick to the default.
Cartoon rectangles
Dissimilar SVG, <canvass>
only supports two primitive shapes: rectangles and paths (lists of points connected by lines). All other shapes must be created by combining one or more paths. Luckily, we have an array of path drawing functions which make information technology possible to etch very circuitous shapes.
Get-go let'south wait at the rectangle. In that location are iii functions that draw rectangles on the canvas:
-
fillRect(ten, y, width, height)
-
Draws a filled rectangle.
-
strokeRect(ten, y, width, acme)
-
Draws a rectangular outline.
-
clearRect(x, y, width, height)
-
Clears the specified rectangular area, making it fully transparent.
Each of these iii functions takes the aforementioned parameters. x
and y
specify the position on the canvas (relative to the origin) of the height-left corner of the rectangle. width
and height
provide the rectangle's size.
Beneath is the describe()
role from the previous page, only now information technology is making use of these iii functions.
Rectangular shape example
function draw ( ) { var canvas = certificate. getElementById ( 'sail' ) ; if (canvas.getContext) { var ctx = canvas. getContext ( '2d' ) ; ctx. fillRect ( 25 , 25 , 100 , 100 ) ; ctx. clearRect ( 45 , 45 , threescore , 60 ) ; ctx. strokeRect ( fifty , 50 , 50 , 50 ) ; } }
This example'southward output is shown below.
The fillRect()
office draws a big blackness square 100 pixels on each side. The clearRect()
function then erases a 60x60 pixel square from the centre, and then strokeRect()
is called to create a rectangular outline 50x50 pixels inside the cleared square.
In upcoming pages nosotros'll see two alternative methods for clearRect()
, and nosotros'll also see how to change the colour and stroke style of the rendered shapes.
Dissimilar the path functions nosotros'll run across in the side by side section, all iii rectangle functions draw immediately to the canvass.
Cartoon paths
Now let'due south look at paths. A path is a list of points, connected by segments of lines that tin be of dissimilar shapes, curved or not, of different width and of dissimilar colour. A path, or fifty-fifty a subpath, can be closed. To make shapes using paths, we accept some extra steps:
- Start, you create the path.
- And then yous use drawing commands to draw into the path.
- One time the path has been created, you can stroke or fill the path to return information technology.
Hither are the functions used to perform these steps:
-
beginPath()
-
Creates a new path. Once created, time to come drawing commands are directed into the path and used to build the path upward.
- Path methods
-
Methods to gear up different paths for objects.
-
closePath()
-
Adds a straight line to the path, going to the showtime of the electric current sub-path.
-
stroke()
-
Draws the shape by stroking its outline.
-
fill()
-
Draws a solid shape by filling the path's content expanse.
The commencement step to create a path is to call the beginPath()
. Internally, paths are stored every bit a list of sub-paths (lines, arcs, etc) which together form a shape. Every fourth dimension this method is called, the list is reset and we can start cartoon new shapes.
Note: When the current path is empty, such as immediately after calling beginPath()
, or on a newly created canvas, the first path construction command is always treated as a moveTo()
, regardless of what it really is. For that reason, y'all will almost ever want to specifically set your starting position after resetting a path.
The second pace is calling the methods that actually specify the paths to be drawn. Nosotros'll run into these soon.
The third, and an optional step, is to telephone call closePath()
. This method tries to close the shape past drawing a straight line from the electric current signal to the kickoff. If the shape has already been airtight or there's only 1 indicate in the list, this part does zero.
Note: When you lot phone call fill up()
, whatsoever open up shapes are closed automatically, so you don't accept to call closePath()
. This is not the example when you lot call stroke()
.
Cartoon a triangle
For example, the code for drawing a triangle would wait something like this:
part draw ( ) { var canvas = certificate. getElementById ( 'canvass' ) ; if (sail.getContext) { var ctx = sail. getContext ( '2d' ) ; ctx. beginPath ( ) ; ctx. moveTo ( 75 , 50 ) ; ctx. lineTo ( 100 , 75 ) ; ctx. lineTo ( 100 , 25 ) ; ctx. fill ( ) ; } }
The result looks like this:
Moving the pen
1 very useful function, which doesn't actually describe anything but becomes function of the path list described above, is the moveTo()
office. You tin probably best retrieve of this as lifting a pen or pencil from i spot on a piece of paper and placing it on the side by side.
-
moveTo(10, y)
-
Moves the pen to the coordinates specified by
ten
andy
.
When the canvas is initialized or beginPath()
is called, yous typically volition desire to apply the moveTo()
function to place the starting point somewhere else. Nosotros could also employ moveTo()
to draw unconnected paths. Take a wait at the smiley face beneath.
To try this for yourself, yous can apply the code snippet beneath. Only paste it into the depict()
part we saw earlier.
role draw ( ) { var canvas = document. getElementById ( 'sail' ) ; if (canvas.getContext) { var ctx = canvas. getContext ( '2d' ) ; ctx. beginPath ( ) ; ctx. arc ( 75 , 75 , l , 0 , Math. PI * 2 , truthful ) ; // Outer circle ctx. moveTo ( 110 , 75 ) ; ctx. arc ( 75 , 75 , 35 , 0 , Math. PI , false ) ; // Oral fissure (clockwise) ctx. moveTo ( 65 , 65 ) ; ctx. arc ( threescore , 65 , 5 , 0 , Math. PI * 2 , true ) ; // Left center ctx. moveTo ( 95 , 65 ) ; ctx. arc ( 90 , 65 , 5 , 0 , Math. PI * two , true ) ; // Right center ctx. stroke ( ) ; } }
The issue looks like this:
If you'd like to come across the connecting lines, you tin can remove the lines that call moveTo()
.
Notation: To learn more than nearly the arc()
role, meet the Arcs department below.
Lines
For drawing direct lines, use the lineTo()
method.
-
lineTo(10, y)
-
Draws a line from the electric current cartoon position to the position specified by
ten
andy
.
This method takes two arguments, x
and y
, which are the coordinates of the line's end point. The starting signal is dependent on previously drawn paths, where the end point of the previous path is the starting point for the post-obit, etc. The starting point can also be changed past using the moveTo()
method.
The example below draws ii triangles, one filled and one outlined.
part draw ( ) { var canvas = document. getElementById ( 'sheet' ) ; if (sheet.getContext) { var ctx = canvas. getContext ( '2d' ) ; // Filled triangle ctx. beginPath ( ) ; ctx. moveTo ( 25 , 25 ) ; ctx. lineTo ( 105 , 25 ) ; ctx. lineTo ( 25 , 105 ) ; ctx. make full ( ) ; // Stroked triangle ctx. beginPath ( ) ; ctx. moveTo ( 125 , 125 ) ; ctx. lineTo ( 125 , 45 ) ; ctx. lineTo ( 45 , 125 ) ; ctx. closePath ( ) ; ctx. stroke ( ) ; } }
This starts by calling beginPath()
to start a new shape path. Nosotros then employ the moveTo()
method to motility the starting point to the desired position. Beneath this, two lines are fatigued which make up ii sides of the triangle.
Yous'll notice the divergence between the filled and stroked triangle. This is, equally mentioned higher up, because shapes are automatically airtight when a path is filled, merely not when they are stroked. If we left out the closePath()
for the stroked triangle, simply two lines would accept been drawn, non a complete triangle.
Arcs
To draw arcs or circles, nosotros apply the arc()
or arcTo()
methods.
-
arc(10, y, radius, startAngle, endAngle, counterclockwise)
-
Draws an arc which is centered at (10, y) position with radius r starting at startAngle and ending at endAngle going in the given direction indicated by counterclockwise (defaulting to clockwise).
-
arcTo(x1, y1, x2, y2, radius)
-
Draws an arc with the given command points and radius, connected to the previous point by a directly line.
Let's have a more detailed expect at the arc
method, which takes vi parameters: x
and y
are the coordinates of the center of the circle on which the arc should be drawn. radius
is self-explanatory. The startAngle
and endAngle
parameters define the outset and cease points of the arc in radians, along the curve of the circle. These are measured from the x axis. The counterclockwise
parameter is a Boolean value which, when true
, draws the arc counterclockwise; otherwise, the arc is drawn clockwise.
Note: Angles in the arc
role are measured in radians, not degrees. To convert degrees to radians you can use the post-obit JavaScript expression: radians = (Math.PI/180)*degrees
.
The following example is a little more complex than the ones we've seen above. It draws 12 different arcs all with different angles and fills.
The ii for
loops are for looping through the rows and columns of arcs. For each arc, we beginning a new path past calling beginPath()
. In the lawmaking, each of the parameters for the arc is in a variable for clarity, but y'all wouldn't necessarily do that in real life.
The ten
and y
coordinates should be clear enough. radius
and startAngle
are fixed. The endAngle
starts at 180 degrees (half a circle) in the first cavalcade and is increased by steps of 90 degrees, culminating in a complete circle in the terminal column.
The statement for the clockwise
parameter results in the first and third row being drawn equally clockwise arcs and the 2nd and fourth row as counterclockwise arcs. Finally, the if
argument makes the tiptop half stroked arcs and the bottom half filled arcs.
Note: This example requires a slightly larger canvas than the others on this page: 150 x 200 pixels.
function draw ( ) { var canvas = document. getElementById ( 'canvass' ) ; if (canvas.getContext) { var ctx = canvas. getContext ( '2d' ) ; for ( var i = 0 ; i < 4 ; i++ ) { for ( var j = 0 ; j < 3 ; j++ ) { ctx. beginPath ( ) ; var x = 25 + j * 50 ; // x coordinate var y = 25 + i * 50 ; // y coordinate var radius = xx ; // Arc radius var startAngle = 0 ; // Starting betoken on circle var endAngle = Math. PI + (Math. PI * j) / 2 ; // Terminate point on circumvolve var counterclockwise = i % ii !== 0 ; // clockwise or counterclockwise ctx. arc (x, y, radius, startAngle, endAngle, counterclockwise) ; if (i > 1 ) { ctx. make full ( ) ; } else { ctx. stroke ( ) ; } } } } }
Bezier and quadratic curves
The side by side type of paths available are Bézier curves, available in both cubic and quadratic varieties. These are more often than not used to draw complex organic shapes.
-
quadraticCurveTo(cp1x, cp1y, 10, y)
-
Draws a quadratic Bézier curve from the electric current pen position to the end point specified past
x
andy
, using the control indicate specified bycp1x
andcp1y
. -
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
-
Draws a cubic Bézier curve from the current pen position to the end point specified by
ten
andy
, using the control points specified by (cp1x
,cp1y
) and (cp2x, cp2y).
The difference between these is that a quadratic Bézier curve has a start and an end bespeak (blue dots) and just one control bespeak (indicated by the red dot) while a cubic Bézier curve uses ii control points.
The x
and y
parameters in both of these methods are the coordinates of the cease point. cp1x
and cp1y
are the coordinates of the first command indicate, and cp2x
and cp2y
are the coordinates of the second control signal.
Using quadratic and cubic Bézier curves tin can exist quite challenging, considering different vector cartoon software like Adobe Illustrator, we don't have direct visual feedback every bit to what we're doing. This makes it pretty hard to draw circuitous shapes. In the following example, we'll be cartoon some simple organic shapes, merely if you have the time and, most of all, the patience, much more complex shapes can be created.
At that place's zip very difficult in these examples. In both cases nosotros see a succession of curves being drawn which finally result in a complete shape.
Quadratic Bezier curves
This example uses multiple quadratic Bézier curves to return a speech communication airship.
function draw ( ) { var sail = document. getElementById ( 'canvas' ) ; if (canvas.getContext) { var ctx = canvas. getContext ( 'second' ) ; // Quadratic curves example ctx. beginPath ( ) ; ctx. moveTo ( 75 , 25 ) ; ctx. quadraticCurveTo ( 25 , 25 , 25 , 62.v ) ; ctx. quadraticCurveTo ( 25 , 100 , 50 , 100 ) ; ctx. quadraticCurveTo ( 50 , 120 , thirty , 125 ) ; ctx. quadraticCurveTo ( 60 , 120 , 65 , 100 ) ; ctx. quadraticCurveTo ( 125 , 100 , 125 , 62.5 ) ; ctx. quadraticCurveTo ( 125 , 25 , 75 , 25 ) ; ctx. stroke ( ) ; } }
Cubic Bezier curves
This example draws a heart using cubic Bézier curves.
function draw ( ) { var canvas = document. getElementById ( 'canvas' ) ; if (sail.getContext) { var ctx = canvas. getContext ( '2d' ) ; // Cubic curves case ctx. beginPath ( ) ; ctx. moveTo ( 75 , 40 ) ; ctx. bezierCurveTo ( 75 , 37 , 70 , 25 , fifty , 25 ) ; ctx. bezierCurveTo ( twenty , 25 , 20 , 62.5 , 20 , 62.5 ) ; ctx. bezierCurveTo ( xx , lxxx , 40 , 102 , 75 , 120 ) ; ctx. bezierCurveTo ( 110 , 102 , 130 , 80 , 130 , 62.5 ) ; ctx. bezierCurveTo ( 130 , 62.five , 130 , 25 , 100 , 25 ) ; ctx. bezierCurveTo ( 85 , 25 , 75 , 37 , 75 , 40 ) ; ctx. fill ( ) ; } }
Rectangles
In addition to the 3 methods we saw in Drawing rectangles, which draw rectangular shapes directly to the canvas, there's likewise the rect()
method, which adds a rectangular path to a currently open path.
-
rect(x, y, width, height)
-
Draws a rectangle whose top-left corner is specified by (
x
,y
) with the specifiedwidth
andheight
.
Before this method is executed, the moveTo()
method is automatically called with the parameters (x,y). In other words, the electric current pen position is automatically reset to the default coordinates.
Making combinations
So far, each example on this page has used but one type of path function per shape. However, at that place'south no limitation to the number or types of paths you can utilise to create a shape. So in this final example, permit's combine all of the path functions to make a set of very famous game characters.
function depict ( ) { var canvas = document. getElementById ( 'sail' ) ; if (sheet.getContext) { var ctx = sail. getContext ( '2d' ) ; roundedRect (ctx, 12 , 12 , 150 , 150 , 15 ) ; roundedRect (ctx, nineteen , 19 , 150 , 150 , 9 ) ; roundedRect (ctx, 53 , 53 , 49 , 33 , 10 ) ; roundedRect (ctx, 53 , 119 , 49 , 16 , 6 ) ; roundedRect (ctx, 135 , 53 , 49 , 33 , ten ) ; roundedRect (ctx, 135 , 119 , 25 , 49 , ten ) ; ctx. beginPath ( ) ; ctx. arc ( 37 , 37 , 13 , Math. PI / 7 , -Math. PI / 7 , false ) ; ctx. lineTo ( 31 , 37 ) ; ctx. fill up ( ) ; for ( var i = 0 ; i < eight ; i++ ) { ctx. fillRect ( 51 + i * 16 , 35 , iv , 4 ) ; } for (i = 0 ; i < 6 ; i++ ) { ctx. fillRect ( 115 , 51 + i * 16 , 4 , 4 ) ; } for (i = 0 ; i < 8 ; i++ ) { ctx. fillRect ( 51 + i * 16 , 99 , four , 4 ) ; } ctx. beginPath ( ) ; ctx. moveTo ( 83 , 116 ) ; ctx. lineTo ( 83 , 102 ) ; ctx. bezierCurveTo ( 83 , 94 , 89 , 88 , 97 , 88 ) ; ctx. bezierCurveTo ( 105 , 88 , 111 , 94 , 111 , 102 ) ; ctx. lineTo ( 111 , 116 ) ; ctx. lineTo ( 106.333 , 111.333 ) ; ctx. lineTo ( 101.666 , 116 ) ; ctx. lineTo ( 97 , 111.333 ) ; ctx. lineTo ( 92.333 , 116 ) ; ctx. lineTo ( 87.666 , 111.333 ) ; ctx. lineTo ( 83 , 116 ) ; ctx. make full ( ) ; ctx.fillStyle = 'white' ; ctx. beginPath ( ) ; ctx. moveTo ( 91 , 96 ) ; ctx. bezierCurveTo ( 88 , 96 , 87 , 99 , 87 , 101 ) ; ctx. bezierCurveTo ( 87 , 103 , 88 , 106 , 91 , 106 ) ; ctx. bezierCurveTo ( 94 , 106 , 95 , 103 , 95 , 101 ) ; ctx. bezierCurveTo ( 95 , 99 , 94 , 96 , 91 , 96 ) ; ctx. moveTo ( 103 , 96 ) ; ctx. bezierCurveTo ( 100 , 96 , 99 , 99 , 99 , 101 ) ; ctx. bezierCurveTo ( 99 , 103 , 100 , 106 , 103 , 106 ) ; ctx. bezierCurveTo ( 106 , 106 , 107 , 103 , 107 , 101 ) ; ctx. bezierCurveTo ( 107 , 99 , 106 , 96 , 103 , 96 ) ; ctx. make full ( ) ; ctx.fillStyle = 'black' ; ctx. beginPath ( ) ; ctx. arc ( 101 , 102 , 2 , 0 , Math. PI * 2 , true ) ; ctx. fill up ( ) ; ctx. beginPath ( ) ; ctx. arc ( 89 , 102 , ii , 0 , Math. PI * ii , true ) ; ctx. fill ( ) ; } } // A utility function to depict a rectangle with rounded corners. function roundedRect ( ctx, x, y, width, height, radius ) { ctx. beginPath ( ) ; ctx. moveTo (ten, y + radius) ; ctx. arcTo (x, y + height, ten + radius, y + acme, radius) ; ctx. arcTo (10 + width, y + elevation, x + width, y + peak - radius, radius) ; ctx. arcTo (x + width, y, ten + width - radius, y, radius) ; ctx. arcTo (x, y, x, y + radius, radius) ; ctx. stroke ( ) ; }
The resulting image looks like this:
We won't get over this in particular, since it's actually surprisingly simple. The most of import things to note are the employ of the fillStyle
property on the drawing context, and the use of a utility role (in this case roundedRect()
). Using utility functions for $.25 of drawing y'all do oft can exist very helpful and reduce the amount of code yous need, besides as its complexity.
Nosotros'll take another look at fillStyle
, in more than particular, later on in this tutorial. Here, all we're doing is using information technology to alter the fill color for paths from the default colour of black to white, and then back once more.
Path2D objects
As we have seen in the concluding instance, in that location can be a series of paths and drawing commands to draw objects onto your canvas. To simplify the code and to amend performance, the Path2D
object, available in recent versions of browsers, lets you lot cache or record these drawing commands. Y'all are able to play back your paths quickly. Let'due south see how nosotros can construct a Path2D
object:
-
Path2D()
-
The
Path2D()
constructor returns a newly instantiatedPath2D
object, optionally with another path every bit an argument (creates a copy), or optionally with a string consisting of SVG path information.
new Path2D ( ) ; // empty path object new Path2D (path) ; // copy from another Path2D object new Path2D (d) ; // path from SVG path information
All path methods like moveTo
, rect
, arc
or quadraticCurveTo
, etc., which nosotros got to know above, are available on Path2D
objects.
The Path2D
API also adds a way to combine paths using the addPath
method. This can exist useful when you want to build objects from several components, for example.
-
Path2D.addPath(path [, transform])
-
Adds a path to the current path with an optional transformation matrix.
Path2D case
In this example, we are creating a rectangle and a circumvolve. Both are stored as a Path2D
object, then that they are available for later usage. With the new Path2D
API, several methods got updated to optionally accept a Path2D
object to employ instead of the current path. Hither, stroke
and fill
are used with a path statement to draw both objects onto the canvass, for example.
function describe ( ) { var canvas = document. getElementById ( 'sail' ) ; if (sail.getContext) { var ctx = canvas. getContext ( '2d' ) ; var rectangle = new Path2D ( ) ; rectangle. rect ( 10 , 10 , fifty , 50 ) ; var circumvolve = new Path2D ( ) ; circle. arc ( 100 , 35 , 25 , 0 , ii * Math. PI ) ; ctx. stroke (rectangle) ; ctx. make full (circle) ; } }
Using SVG paths
Another powerful feature of the new canvas Path2D
API is using SVG path information to initialize paths on your sail. This might allow you lot to pass around path data and re-use them in both, SVG and canvas.
The path will move to point (M10 ten
) and and so move horizontally 80 points to the right (h 80
), then 80 points downward (5 80
), so 80 points to the left (h -lxxx
), and then back to the start (z
). You can run across this case on the Path2D
constructor page.
var p = new Path2D ( 'M10 x h fourscore 5 80 h -80 Z' ) ;
- « Previous
- Side by side »
Source: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes
0 Response to "Javascript Draw Circle on Canvas"
إرسال تعليق