How to let the user draw an ellipse? - javascript

I'm making a simple paint program with javascript. The circle-tool is working as intended, but how do I add a tool for drawing an ellipse/oval?
I have reused much of the code for making the different tools (pencil, line, rectangle, and circle), and so far so good. But I can't get the code for drawing the ellipse right.
Here's the current and working code for drawing a circle filled with a random color:
var radius = Math.max(
Math.abs(ev._x - tool.x0),
Math.abs(ev._y - tool.y0)
) / 2;
var x = Math.min(ev._x, tool.x0) + radius;
var y = Math.min(ev._y, tool.y0) + radius;
context.fillStyle = 'hsl(' + 360 * Math.random() + ', 85%, 50%)';
context.beginPath();
context.arc(x, y, radius, 0, Math.PI*2, false);
context.stroke();
context.closePath();
context.fill();
I've tried to integrate it with the code already in use and the context.scale, but I don't get it right:
var radius = Math.max(
Math.abs(ev._x - tool.x0),
Math.abs(ev._y - tool.y0)
) / 2;
var radius2 = ;
var x = Math.min(ev._x, tool.x0) + radius;
var y = Math.min(ev._y, tool.y0) + radius;
context.save();
context.scale(1, radius2/radius);
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI);
context.restore();
context.lineWidth=2;
context.strokeStyle="#000";
context.stroke();
Is the var radius correct, and do I write the var radius2? The entire code is here JS Bin

The x attribute defines the x coordinate of the center of the ellipse
The y attribute defines the y coordinate of the center of the ellipse
The radiusX attribute defines the horizontal radius
The ry attribute defines the vertical radius
Image for your reference

Related

Using trigonometry to animate HTML5 canvas, but how to position this square?

Sometimes you wish you could go back in time to tell your younger self that maths are indeed important! But I doubt I would've listened back then. I've been playing with trigonometry lately for animation purposes with the HTML5 canvas in this particular example.
It's a super simple animation: It positions an arc in a circular manner around the center of the canvas. The X and Y positions are calculated based upon the basic trigonometry functions sinus and cosinus. "SohCahToa". I think I'm starting to get it. But somehow I cannot figure out how to draw a square in the middle of one of the triangular sides.
let radius = 200;
let angle = 0;
x = centerX + Math.cos(angle) * radius;
ctx.beginPath();
ctx.fillRect(x/2, centerY, 20, 20);
https://codepen.io/melvinidema/pen/wvKPepa?editors=1010
So the arc is drawn by adding up the center of the canvas with the
rework formulas: (co)sinus - for X = Cos, for Y = Sin) of the angle times the radius of the circle.
If we only take the X position (red line) and want to draw the square half of the position of the arc. ( So in the middle of the red line ) we should just be able to divide the freshly calculated X position by two right? But if I do that, the square is magically drawn completely outside the circle.
What's happening? Why does it behave like this? And what calculation should I use instead for the square to position in the middle of the red line throughout the animation?
Thanks in advance!
Your x defined as:
x = centerX + Math.cos(angle) * radius;
but when you want to divide by 2, you just need to divide the Math.cos(angle) * radius, while the centerX is the zero point, and its stand as it is.
So the rect should be placed at:
centerX + Math.cos(angle)/2
Also, I think will be better if you reduce half of the rect width, and get:
centerX + Math.cos(angle)/2 - 10
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
let radius = 200;
function frame(angle) {
const cx = canvas.width / 2,
cy = canvas.height / 2,
x = Math.cos(angle) * radius,
y = Math.sin(angle) * radius;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.lineTo(cx+x, cy+y);
ctx.lineTo(cx+x, cy);
ctx.lineTo(cx, cy);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.arc(cx+x, cy+y, 10, 0, Math.PI*2);
ctx.fill();
ctx.fillRect(cx + x/2 - 10, cy - 10, 20, 20);
ctx.closePath();
requestAnimationFrame(()=>frame(angle+.03));
}
frame(0)
canvas {
display: block;
max-height: 100vh;
margin: auto;
}
<canvas width="500" height="500"></canvas>

Drawing a angle / arc, filled with a radiant in canvas?

Problem: Im drawing a spaceship on the canvas. Upon hovering over it's x/y, im drawing an arc on the canvas, indicating the starships weapons angle and range (considering the starships current Baring/facing). Currently the determined angle is being drawn in green and extends as far as the weapons range value allows.
However, i would like to use a gradiant to fill the determined arc to indicate a drop-off in accuracy (i.e. gradiant begins at green, moves to orange, turns red the further away from the starships Position the angle is).
However, i dont know how i could replace my stock ctx.fill() on the drawn arc with a gradiant.
var ship {
loc: {x, y}, // lets say 100, 100
facing: facing // lets say facing 0, i.e. straight right
weapons: objects (range, startArc, endArc) // lets say 50, 300, 60 -> 120 degree angle, so -60 and +60 from facing (0/360)
}
for (var i = 0; i < weapon.arc.length; i++){
var p1 = getPointInDirection(weapon.range, weapon.arc[i][0] + angle, pos.x, pos.y);
var p2 = getPointInDirection(weapon.range, weapon.arc[i][1] + angle, pos.x, pos.y)
var dist = getDistance( {x: pos.x, y: pos.y}, p1);
var rad1 = degreeToRadian(weapon.arc[i][0] + angle);
var rad2 = degreeToRadian(weapon.arc[i][1] + angle);
fxCtx.beginPath();
fxCtx.moveTo(pos.x, pos.y);
fxCtx.lineTo(p1.x, p1.y);
fxCtx.arc(pos.x, pos.y, dist, rad1, rad2, false);
fxCtx.closePath();
fxCtx.globalAlpha = 0.3;
fxCtx.fillStyle = "green";
fxCtx.fill();
fxCtx.globalAlpha = 1;
}
is it possible to replace the arc/globalalpha/fill so use a gradiant flow instead of it being colored fixed and if so, how ?
thanks
To fill an arc with a gradient, animated just for the fun.
Uses a radial gradient and set colour stops as a fraction of distance.
The function createRadialGradient takes 6 numbers the position x,y and start radius and the position x,y and end radius of the gradient.
Colour stops are added via the gradient object addColorStop function that takes a value 0 inner to 1 outer part of the gradient and the colour as a CSS color string. "#F00" or "rgba(200,0,0,0.5)" or "RED"
Then just use the gradient as the fill style.
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
function update(time) {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// position of zones in fractions
var posRed = 0.8 + Math.sin(time / 100) * 0.091;
var posOrange = 0.5 + Math.sin(time / 200) * 0.2;
var posGreen = 0.1 + Math.sin(time / 300) * 0.1;
var pos = {
x: canvas.width / 2,
y: canvas.height / 2
};
var dist = 100;
var ang1 = 2 + Math.sin(time / 1000) * 0.5;
var ang2 = 4 + Math.sin(time / 1300) * 0.5;
var grad = ctx.createRadialGradient(pos.x, pos.y, 0, pos.x, pos.y, dist);
grad.addColorStop(0, "#0A0");
grad.addColorStop(posGreen, "#0A0");
grad.addColorStop(posOrange, "#F80");
grad.addColorStop(posRed, "#F00");
grad.addColorStop(1, "#000");
ctx.fillStyle = grad;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
ctx.arc(pos.x, pos.y, dist, ang1, ang2);
ctx.fill();
requestAnimationFrame(update);
}
requestAnimationFrame(update);

get height of oval drawn on canvas

I want to get height of oval drawn on canvas.Below is my code to draw oval on canvas.
function drawOval(startX, startY, endX, endY, strokeColor) {
x = endX;
y = endY;
context.beginPath();
context.strokeStyle = strokeColor;
context.moveTo(startX, startY + (y - startY) / 2);
context.bezierCurveTo(startX, startY, x, startY, x, startY + (y - startY) / 2);
context.bezierCurveTo(x, y, startX, y, startX, startY + (y - startY) / 2);
context.stroke();
context.fillStyle = strokeColor;
context.fill();
}
I would suggest drawing the oval in a different way:
Bezier is more complex and performance hungry
Bezier does not draw an accurate oval (ellipse)
More difficult to extract certain points for measure without using a manual formula.
To use a different approach which is signature compatible with what you have you could do:
function drawOval(startX, startY, endX, endY, strokeColor) {
var rx = (endX - startX) * 0.5, // get radius for x
ry = (endY - startY) * 0.5, // get radius for y
cx = startX + rx, // get center position for ellipse
cy = startY + ry,
a = 0, // current angle
step = 0.01, // angle step
pi2 = Math.PI * 2;
context.beginPath();
context.strokeStyle = strokeColor;
context.moveTo(cx + rx, cy); // initial point at 0 deg.
for(; a < pi2; a += step)
context.lineTo(cx + rx * Math.cos(a), // create ellipse path
cy + ry * Math.sin(a));
context.closePath(); // close for stroke
context.stroke();
context.fillStyle = strokeColor;
context.fill();
}
Live demo here
Now you will get height (and width) simply by doing:
var width = Math.abs(endX - startX),
height = Math.abs(endY - startY);

Cutting irregular shape on image

I am trying to cut an image into a particular shape using the canvas clip() method.
I have followed the following steps to do so:
Draw a rectangle.
Draw semi circles on each side. The right and bottom semi circles protrude outwards and the left and top semi circles are inwards.
The code snippet is provided below:
var canvasNode = this.hasNode();
var ctx = canvasNode && canvasNode.getContext('2d');
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0, 512, 384);
};
image.src = "images/image.png";
var startX = 200;
var startY = 0;
var rectWidth = 150;
var rectHeight = 150;
var radius = 30;
//Main Rect
ctx.rect(startX, startY, rectWidth, rectHeight);
//Right arc
ctx.moveTo(startX+=rectWidth, startY+=(rectHeight/2));
ctx.arc(startX, startY, radius, 3 * Math.PI / 2, Math.PI / 2, false);
//Left arc
ctx.moveTo(startX-=(rectWidth / 2), startY+=(rectHeight / 2));
ctx.arc(startX, startY, radius, 0, Math.PI, true);
ctx.moveTo(startX-=(rectWidth / 2), startY-=(rectWidth / 2));
ctx.arc(startX, startY, radius, 3 * Math.PI / 2, Math.PI / 2, false);
ctx.clip();
The image that I am using is of size 800 x 600 (png). Please help me understand what I am doing wrong here.
Firstly, why are you using clip? You are currently just drawing semicircles, which works without clip.
Secondly, you are creating paths and clipping, but you never stroke the path. As a result, you won't see anything on the screen.
If you just stroke instead of clip, it works partially for me: http://jsfiddle.net/r6yAN/. You did not include the top semicircle though.
Edit: It seems like you're not using the best way of clipping. You draw a rectangle, but this also includes a line in the semicircle. You'd be better off if you draw each line/arc yourself like this: http://jsfiddle.net/CH6qB/6/.
The main idea is to move from point to point as in this image:
So first start at (startX, startY), then a line to (startX + lineWidth, startY), then an arc at (startX + rectWidth / 2, startY) from pi to 0 (counterclockwise), etc.
If you want to stroke the path as well after having drawn the image, it is a good idea to unclip again. Otherwise, the stroke will not be of great quality.
var canvasNode = document.getElementById('cv');
var ctx = canvasNode && canvasNode.getContext('2d');
var image = new Image();
image.onload = function() {
// draw the image, region has been clipped
ctx.drawImage(image, startX, startY);
// restore so that a stroke is not affected by clip
// (restore removes the clipping because we saved the path without clip below)
ctx.restore();
ctx.stroke();
};
image.src = "http://www.lorempixum.com/200/200/";
var startX = 200;
var startY = 0;
var rectWidth = 150;
var rectHeight = 150;
var radius = 30;
var lineWidth = rectWidth / 2 - radius;
var lineHeight = rectHeight / 2 - radius;
// typing pi is easier than Math.PI each time
var pi = Math.PI;
ctx.moveTo(startX, startY);
ctx.lineTo(startX + lineWidth, startY);
ctx.arc(startX + rectWidth / 2, startY,
radius,
pi, 0, true);
ctx.lineTo(startX + rectWidth, startY);
ctx.lineTo(startX + rectWidth, startY + lineHeight);
ctx.arc(startX + rectWidth, startY + rectHeight / 2,
radius,
-pi / 2, pi / 2, false);
ctx.lineTo(startX + rectWidth, startY + rectHeight);
ctx.lineTo(startX + rectWidth - lineWidth, startY + rectHeight);
ctx.arc(startX + rectWidth / 2, startY + rectHeight,
radius,
0, pi, false);
ctx.lineTo(startX, startY + rectHeight);
ctx.lineTo(startX, startY + rectHeight - lineHeight);
ctx.arc(startX, startY + rectHeight / 2,
radius,
pi/2, pi*3/2, true);
ctx.lineTo(startX, startY);
ctx.save(); // Save the current state without clip
ctx.clip();

How to draw an oval in html5 canvas?

There doesnt seem to be a native function to draw an oval-like shape. Also i am not looking for the egg-shape.
Is it possible to draw an oval with 2 bezier curves?
Somebody expierenced with that?
My purpose is to draw some eyes and actually im just using arcs.
Thanks in advance.
Solution
So scale() changes the scaling for all next shapes.
Save() saves the settings before and restore is used to restore the settings to draw new shapes without scaling.
Thanks to Jani
ctx.save();
ctx.scale(0.75, 1);
ctx.beginPath();
ctx.arc(20, 21, 10, 0, Math.PI*2, false);
ctx.stroke();
ctx.closePath();
ctx.restore();
updates:
scaling method can affect stroke width appearance
scaling method done right can keep stroke width intact
canvas has ellipse method that Chrome now supports
added updated tests to JSBin
JSBin Testing Example (updated to test other's answers for comparison)
Bezier - draw based on top left containing rect and width/height
Bezier with Center - draw based on center and width/height
Arcs and Scaling - draw based on drawing circle and scaling
see Deven Kalra's answer
Quadratic Curves - draw with quadratics
test appears to not draw quite the same, may be implementation
see oyophant's answer
Canvas Ellipse - using W3C standard ellipse() method
test appears to not draw quite the same, may be implementation
see Loktar's answer
Original:
If you want a symmetrical oval you could always create a circle of radius width, and then scale it to the height you want (edit: notice this will affect stroke width appearance - see acdameli's answer), but if you want full control of the ellipse here's one way using bezier curves.
<canvas id="thecanvas" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById('thecanvas');
if(canvas.getContext)
{
var ctx = canvas.getContext('2d');
drawEllipse(ctx, 10, 10, 100, 60);
drawEllipseByCenter(ctx, 60,40,20,10);
}
function drawEllipseByCenter(ctx, cx, cy, w, h) {
drawEllipse(ctx, cx - w/2.0, cy - h/2.0, w, h);
}
function drawEllipse(ctx, x, y, w, h) {
var kappa = .5522848,
ox = (w / 2) * kappa, // control point offset horizontal
oy = (h / 2) * kappa, // control point offset vertical
xe = x + w, // x-end
ye = y + h, // y-end
xm = x + w / 2, // x-middle
ym = y + h / 2; // y-middle
ctx.beginPath();
ctx.moveTo(x, ym);
ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
//ctx.closePath(); // not used correctly, see comments (use to close off open path)
ctx.stroke();
}
</script>
Here is a simplified version of solutions elsewhere. I draw a canonical circle, translate and scale and then stroke.
function ellipse(context, cx, cy, rx, ry){
context.save(); // save state
context.beginPath();
context.translate(cx-rx, cy-ry);
context.scale(rx, ry);
context.arc(1, 1, 1, 0, 2 * Math.PI, false);
context.restore(); // restore to original state
context.stroke();
}
There is now a native ellipse function for canvas, very similar to the arc function although now we have two radius values and a rotation which is awesome.
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise)
Live Demo
ctx.ellipse(100, 100, 10, 15, 0, 0, Math.PI*2);
ctx.fill();
Only seems to work in Chrome currently
The bezier curve approach is great for simple ovals. For more control, you can use a loop to draw an ellipse with different values for the x and y radius (radiuses, radii?).
Adding a rotationAngle parameter allows the oval to be rotated around its center by any angle. Partial ovals can be drawn by changing the range (var i) over which the loop runs.
Rendering the oval this way allows you to determine the exact x,y location of all points on the line. This is useful if the postion of other objects depend on the location and orientation of the oval.
Here is an example of the code:
for (var i = 0 * Math.PI; i < 2 * Math.PI; i += 0.01 ) {
xPos = centerX - (radiusX * Math.sin(i)) * Math.sin(rotationAngle * Math.PI) + (radiusY * Math.cos(i)) * Math.cos(rotationAngle * Math.PI);
yPos = centerY + (radiusY * Math.cos(i)) * Math.sin(rotationAngle * Math.PI) + (radiusX * Math.sin(i)) * Math.cos(rotationAngle * Math.PI);
if (i == 0) {
cxt.moveTo(xPos, yPos);
} else {
cxt.lineTo(xPos, yPos);
}
}
See an interactive example here: http://www.scienceprimer.com/draw-oval-html5-canvas
You could also try using non-uniform scaling. You can provide X and Y scaling, so simply set X or Y scaling larger than the other, and draw a circle, and you have an ellipse.
You need 4 bezier curves (and a magic number) to reliably reproduce an ellipse. See here:
www.tinaja.com/glib/ellipse4.pdf
Two beziers don't accurately reproduce an ellipse. To prove this, try some of the 2 bezier solutions above with equal height and width - they should ideally approximate a circle but they won't. They'll still look oval which goes to prove they aren't doing what they are supposed to.
Here's something that should work:
http://jsfiddle.net/BsPsj/
Here's the code:
function ellipse(cx, cy, w, h){
var ctx = canvas.getContext('2d');
ctx.beginPath();
var lx = cx - w/2,
rx = cx + w/2,
ty = cy - h/2,
by = cy + h/2;
var magic = 0.551784;
var xmagic = magic*w/2;
var ymagic = h*magic/2;
ctx.moveTo(cx,ty);
ctx.bezierCurveTo(cx+xmagic,ty,rx,cy-ymagic,rx,cy);
ctx.bezierCurveTo(rx,cy+ymagic,cx+xmagic,by,cx,by);
ctx.bezierCurveTo(cx-xmagic,by,lx,cy+ymagic,lx,cy);
ctx.bezierCurveTo(lx,cy-ymagic,cx-xmagic,ty,cx,ty);
ctx.stroke();
}
I did a little adaptation of this code (partially presented by Andrew Staroscik) for peoplo who do not want a so general ellipse and who have only the greater semi-axis and the excentricity data of the ellipse (good for astronomical javascript toys to plot orbits, for instance).
Here you go, remembering that one can adapt the steps in i to have a greater precision in the drawing:
/* draw ellipse
* x0,y0 = center of the ellipse
* a = greater semi-axis
* exc = ellipse excentricity (exc = 0 for circle, 0 < exc < 1 for ellipse, exc > 1 for hyperbole)
*/
function drawEllipse(ctx, x0, y0, a, exc, lineWidth, color)
{
x0 += a * exc;
var r = a * (1 - exc*exc)/(1 + exc),
x = x0 + r,
y = y0;
ctx.beginPath();
ctx.moveTo(x, y);
var i = 0.01 * Math.PI;
var twoPi = 2 * Math.PI;
while (i < twoPi) {
r = a * (1 - exc*exc)/(1 + exc * Math.cos(i));
x = x0 + r * Math.cos(i);
y = y0 + r * Math.sin(i);
ctx.lineTo(x, y);
i += 0.01;
}
ctx.lineWidth = lineWidth;
ctx.strokeStyle = color;
ctx.closePath();
ctx.stroke();
}
My solution is a bit different than all of these. Closest I think is the most voted answer above though, but I think this way is a bit cleaner and easier to comprehend.
http://jsfiddle.net/jaredwilli/CZeEG/4/
function bezierCurve(centerX, centerY, width, height) {
con.beginPath();
con.moveTo(centerX, centerY - height / 2);
con.bezierCurveTo(
centerX + width / 2, centerY - height / 2,
centerX + width / 2, centerY + height / 2,
centerX, centerY + height / 2
);
con.bezierCurveTo(
centerX - width / 2, centerY + height / 2,
centerX - width / 2, centerY - height / 2,
centerX, centerY - height / 2
);
con.fillStyle = 'white';
con.fill();
con.closePath();
}
And then use it like this:
bezierCurve(x + 60, y + 75, 80, 130);
There are a couple use examples in the fiddle, along with a failed attempt to make one using quadraticCurveTo.
I like the Bezier curves solution above. I noticed the scale also affects the line width so if you're trying to draw an ellipse that is wider than it is tall, your top and bottom "sides" will appear thinner than your left and right "sides"...
a good example would be:
ctx.lineWidth = 4;
ctx.scale(1, 0.5);
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI * 2, false);
ctx.stroke();
you should notice the width of the line at the peak and valley of the ellipse are half as wide as at the left and right apexes (apices?).
Chrome and Opera support ellipse method for canvas 2d context, but IE,Edge,Firefox and Safari don't support it.
We can implement the ellipse method by JS or use a third-party polyfill.
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise)
Usage example:
ctx.ellipse(20, 21, 10, 10, 0, 0, Math.PI*2, true);
You can use a canvas-5-polyfill to provide ellipse method.
Or just paste some js code to provide ellipse method:
if (CanvasRenderingContext2D.prototype.ellipse == undefined) {
CanvasRenderingContext2D.prototype.ellipse = function(x, y, radiusX, radiusY,
rotation, startAngle, endAngle, antiClockwise) {
this.save();
this.translate(x, y);
this.rotate(rotation);
this.scale(radiusX, radiusY);
this.arc(0, 0, 1, startAngle, endAngle, antiClockwise);
this.restore();
}
}
Yes, it is possible with two bezier curves - here's a brief tutorial/example:
http://www.williammalone.com/briefs/how-to-draw-ellipse-html5-canvas/
Since nobody came up with an approach using the simpler quadraticCurveTo I am adding a solution for that. Simply replace the bezierCurveTo calls in the #Steve's answer with this:
ctx.quadraticCurveTo(x,y,xm,y);
ctx.quadraticCurveTo(xe,y,xe,ym);
ctx.quadraticCurveTo(xe,ye,xm,ye);
ctx.quadraticCurveTo(x,ye,x,ym);
You may also remove the closePath. The oval is looking slightly different though.
This is another way of creating an ellipse like shape, although it uses the "fillRect()" function this can be used be changing the arguments in the fillRect() function.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sine and cosine functions</title>
</head>
<body>
<canvas id="trigCan" width="400" height="400"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("trigCan"), ctx = canvas.getContext('2d');
for (var i = 0; i < 360; i++) {
var x = Math.sin(i), y = Math.cos(i);
ctx.stroke();
ctx.fillRect(50 * 2 * x * 2 / 5 + 200, 40 * 2 * y / 4 + 200, 10, 10, true);
}
</script>
</body>
</html>
With this you can even draw segments of an ellipse:
function ellipse(color, lineWidth, x, y, stretchX, stretchY, startAngle, endAngle) {
for (var angle = startAngle; angle < endAngle; angle += Math.PI / 180) {
ctx.beginPath()
ctx.moveTo(x, y)
ctx.lineTo(x + Math.cos(angle) * stretchX, y + Math.sin(angle) * stretchY)
ctx.lineWidth = lineWidth
ctx.strokeStyle = color
ctx.stroke()
ctx.closePath()
}
}
http://jsfiddle.net/FazAe/1/
Here's a function I wrote that uses the same values as the ellipse arc in SVG. X1 & Y1 are the last coordinates, X2 & Y2 are the end coordinates, radius is a number value and clockwise is a boolean value. It also assumes your canvas context has already been defined.
function ellipse(x1, y1, x2, y2, radius, clockwise) {
var cBx = (x1 + x2) / 2; //get point between xy1 and xy2
var cBy = (y1 + y2) / 2;
var aB = Math.atan2(y1 - y2, x1 - x2); //get angle to bulge point in radians
if (clockwise) { aB += (90 * (Math.PI / 180)); }
else { aB -= (90 * (Math.PI / 180)); }
var op_side = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)) / 2;
var adj_side = Math.sqrt(Math.pow(radius, 2) - Math.pow(op_side, 2));
if (isNaN(adj_side)) {
adj_side = Math.sqrt(Math.pow(op_side, 2) - Math.pow(radius, 2));
}
var Cx = cBx + (adj_side * Math.cos(aB));
var Cy = cBy + (adj_side * Math.sin(aB));
var startA = Math.atan2(y1 - Cy, x1 - Cx); //get start/end angles in radians
var endA = Math.atan2(y2 - Cy, x2 - Cx);
var mid = (startA + endA) / 2;
var Mx = Cx + (radius * Math.cos(mid));
var My = Cy + (radius * Math.sin(mid));
context.arc(Cx, Cy, radius, startA, endA, clockwise);
}
If you want the ellipse to fully fit inside a rectangle, it's really like this:
function ellipse(canvasContext, x, y, width, height){
var z = canvasContext, X = Math.round(x), Y = Math.round(y), wd = Math.round(width), ht = Math.round(height), h6 = Math.round(ht/6);
var y2 = Math.round(Y+ht/2), xw = X+wd, ym = Y-h6, yp = Y+ht+h6, cs = cards, c = this.card;
z.beginPath(); z.moveTo(X, y2); z.bezierCurveTo(X, ym, xw, ym, xw, y2); z.bezierCurveTo(xw, yp, X, yp, X, y2); z.fill(); z.stroke();
return z;
}
Make sure your canvasContext.fillStyle = 'rgba(0,0,0,0)'; for no fill with this design.

Categories

Resources