Search code examples
rustgraphicspie-chartellipse

Nannou - How to draw a pie (part of an ellipse)?


I'm new to the rust library Nannou and I'm trying to draw pie chart. I know that in javascript you can specify the amount of the ellipse via:

ctx.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise);

I couldn't however find anything similar in Nannou like:

draw.ellipse().angle(PI);

Solution

  • The nannou::draw::primitive::ellipse::Ellipse does not support sections.

    However you can use the Section from nannou::geom::Ellipse.

    Here is a simple example:

    use nannou::{
        geom::{Ellipse, Tri},
        prelude::*,
    };
    
    fn main() {
        nannou::sketch(view).run()
    }
    
    fn view(app: &App, frame: Frame) {
        let draw = app.draw();
        let win = app.window_rect();
    
        draw.background().color(CORNFLOWERBLUE);
    
        let t = app.time;
    
        let radius = if win.h() < win.w() {
            win.w() / 3f32
        } else {
            win.h() / 3f32
        };
    
        let section = Ellipse::new(Rect::from_x_y_w_h(0f32, 0f32, radius, radius), 120f32)
            .section(0f32, t.sin() * 2f32 * std::f32::consts::PI);
    
        let triangles = section.trangles();
        let mut tris = Vec::new();
        for t in triangles {
            tris.push(Tri([
                [t.0[0][0], t.0[0][1], 0f32],
                [t.0[1][0], t.0[1][1], 0f32],
                [t.0[2][0], t.0[2][1], 0f32],
            ]));
        }
    
        draw.mesh().tris(tris.into_iter()).color(RED);
    
        draw.to_frame(app, &frame).unwrap();
    }