More Canvas Context Shapes

MJS 2015-09-15

The javascript canvas context has existing methods to draw any shape you want using ctx.moveTo and ctx.lineTo methods, as well as predefined common shapes ctx.rect and ctx.arc. Rather than piece together other basic shape from these, here I add a few more methods to draw the rest of the common primitives, polygons, stars, rounded rectangles, and shape (from an array of points). I do not claim this work is unique, as each is individually googleable or you might just invent it yourself for your own tasks. This page can be a useful resource for those people searching for a quick method or two.

I try and keep to the same style of API as the existing methods to reduce any leaning overhead.

Polygons

ctx.polygon(x,y,radius,number_of_sides,rotation_angle)

Drawing a regular n-sided shape. It starts and closes a complete path. You would fill and stroke the path using the usual ctx.fill and ctx.stroke methods. The animation above is just varying the size, angle, and number of sides. You can see I don't limit the number of sides to an integer, but the non-int sides are not nice.




Star

ctx.star(x,y,radius,ratio,number_of_sides,rotation_angle)

This is very similar to the polygon, but it has an additional parameter of the ratio of the inner spokes to the outer spokes. Ratios bigger than 1 will grow the star. A ratio of exactly 1 will mimic a polygon of 2*n sides.




Rounded Rectangles

ctx.roundRect(x,y,width,height,radius) similar to rect the x and y are the top left corner. Radius is a number or an array of four numbers [top_left,top_right,lower_right,lower_left] for individual control.

This begins and closes a path that can be filled or stroked. The animated versions show changing the radius, or individual radiuses (radii). The radius is limited by the size of the rectangle, so that if the dimensions are to small, the radius is shrunk.




It is possible to draw a rounded rectangle using quadraticCurveTo too. This produces a very similar shape. In my speed tests, to see which draws the fastest, there is no significant difference. The arc method has slightly tighter corners, but a more round shape, the quadraticCurveTo is a bit tighter, but smoother on the transition between the strait edge and the corner.




Shape

ctx.shape(x,y,points,scale,rotate)

Here the shape is a list of point, [x,y], like:


var LShape = [ [0,0],[5,0],[5,5],[-5,5],[-5,-10],[0,-10] ];

And ctx.shape will draw straight lines between them.




The shape drawing code is very open to imporvements. A system where you can also define what method should be used to draw between the points will open up many more possiblities.

MJS 2015