Ellipse

Small util to draw ellipses

Log in to post a comment.

const turtle = new Turtle();

const x = 0; // min=-30, max=30, step=1
const y = 0; // min=-30, max=30, step=1
const radiusX = 50; // min=1, max=100, step=1
const radiusY = 25; // min=1, max=100, step=1
const angle = 0; // min=0, max=6.28, step=0.01
const segments = 25; // min=3, max=100, step=1

const ellipsePoints = ellipse(x, y, radiusX, radiusY, angle, segments);

function walk() {
    // line from center
    const center = [x,y];
    turtle.jump(center);
    turtle.goto(ellipsePoints[0]);
    
    circle(center);
    
    // points
    drawPoints(ellipsePoints);
    
    // visualize segments
    drawDebugCircles(ellipsePoints);
}

function drawPoints(pts) {
    let p = pts[pts.length-1];
    turtle.jump(p);
    pts.forEach(p => turtle.goto(p));
}
function drawDebugCircles(pts,radius = 0.75) {
    pts.forEach(p => circle(p, radius));
}
function circle(p,radius = 1) {
    turtle.jump(p[0],p[1]-radius);
    turtle.circle(radius);
}
function ellipse(x = 0, y = 0, radiusX = 40, radiusY = 20, angle = 0, segments = 15) {
    return Array.from({length: segments}, (_, i) => (i / segments) * Math.PI*2).map(ang => ([
        x - (radiusY * Math.sin(ang)) * Math.sin(angle) + (radiusX * Math.cos(ang)) * Math.cos(angle),
        y + (radiusX * Math.cos(ang)) * Math.sin(angle) + (radiusY * Math.sin(ang)) * Math.cos(angle),
    ]));
}