// compute point on ellipse from angle around ellipse (theta)
function arc(theta, cx, cy, rx, ry, alpha)
{
// theta is angle in radians around arc
// alpha is angle of rotation of ellipse in radians
var cos = Math.cos(alpha), sin = Math.sin(alpha),
x = rx*Math.cos(theta), y = ry*Math.sin(theta);
return {
x: cx + cos*x - sin*y,
y: cy + sin*x + cos*y
};
}
function bb_ellipse(cx, cy, rx, ry, alpha)
{
var tan = Math.tan(alpha),
p1, p2, p3, p4, theta,
xmin, ymin, xmax, ymax
;
// find min/max from zeroes of directional derivative along x and y
// along x axis
theta = Math.atan2(-ry*tan, rx);
// get point for this theta
p1 = arc(theta, cx, cy, rx, ry, alpha);
// get anti-symmetric point
p2 = arc(theta + Math.PI, cx, cy, rx, ry, alpha);
// along y axis
theta = Math.atan2(ry, rx*tan);
// get point for this theta
p3 = arc(theta, cx, cy, rx, ry, alpha);
// get anti-symmetric point
p4 = arc(theta + Math.PI, cx, cy, rx, ry, alpha);
// compute min/max values
ymin = Math.min(p3.y, p4.y)
xmin = Math.min(p1.x, p2.x);
ymax = Math.max(p3.y, p4.y);
xmax = Math.max(p1.x, p2.x);
// return bounding box vertices
return [
{x: xmin, y: ymin},
{x: xmax, y: ymin},
{x: xmax, y: ymax},
{x: xmin, y: ymax}
];
}
var cx = 120, cy = 120, rx = 100, ry = 40, alpha = -45;
function ellipse(cx, cy, rx, ry, alpha)
{
// create an ellipse
const ellipse = document.createElementNS('http://www.w3.org/2000/svg', 'ellipse');
ellipse.setAttribute('stroke', 'black');
ellipse.setAttribute('fill', 'none');
ellipse.setAttribute('cx', cx);
ellipse.setAttribute('cy', cy);
ellipse.setAttribute('rx', rx);
ellipse.setAttribute('ry', ry);
ellipse.setAttribute('transform', 'rotate('+alpha+' '+cx+' '+cy+')');
document.getElementById('svg').appendChild(ellipse);
// create the bounding box
const bb = bb_ellipse(cx, cy, rx, ry, /*angle in radians*/ alpha*Math.PI/180);
const polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
polygon.setAttribute('stroke', 'red');
polygon.setAttribute('fill', 'none');
polygon.setAttribute('points', bb.map(p => String(p.x) + ' ' + String(p.y)).join(' '));
document.getElementById('svg').appendChild(polygon);
}
ellipse(cx, cy, rx, ry, alpha);
<svg xmlns="http://www.w3.org/2000/svg" id="svg" style="position:relative;width:240px;height:240px" viewBox="0 0 240 240"></svg>