Time for action – adding an Ellipse tool
Let's use some transformations to draw an ellipse in Canvas Pad. An ellipse is basically a squashed circle. We can use the scale()
method to change the scale of either the x or y axis before drawing a circle to squash it into an ellipse. Let's add a drawEllipse()
method to the Canvas2D
object. It takes a center point, an end point, and a Boolean to determine if it should be filled:
this.drawEllipse = function(center, endPoint, fill) { var rx = Math.abs(endPoint.x - center.x); var ry = Math.abs(endPoint.y - center.y); var radius = Math.max(rx, ry); var scaleX = rx / radius; var scaleY = ry / radius; context.save(); context.translate(center.x, center.y); context.scale(scaleX, scaleY); context.beginPath(); context.arc(0, 0, radius, 0, Math.PI * 2, true); context.closePath(); if (fill) context.fill(); else context.stroke(); context.restore(); return this; };
There's a lot going on in here...