Skip to content

Instantly share code, notes, and snippets.

@dzil123
Last active July 31, 2021 12:32
Show Gist options
  • Save dzil123/f52f4d554c570188ddcf73483a2dc292 to your computer and use it in GitHub Desktop.
Save dzil123/f52f4d554c570188ddcf73483a2dc292 to your computer and use it in GitHub Desktop.
use nannou::prelude::*;
fn main() {
nannou::app(model).run();
}
struct Model {
svg_render_frame: u64,
}
fn model(app: &App) -> Model {
app.new_window()
.mouse_pressed(mouse_pressed)
.view(view)
.build()
.unwrap();
Model {
svg_render_frame: 0,
}
}
fn mouse_pressed(app: &App, model: &mut Model, button: MouseButton) {
if let MouseButton::Left = button {
model.svg_render_frame = app.elapsed_frames() + 1;
}
}
fn view(app: &App, model: &Model, frame: Frame) {
let draw = example_draw(app);
if model.svg_render_frame == app.elapsed_frames() {
nannou::draw::renderer::svg::render_and_save(
app.main_window().rect(),
&draw.clone(),
captured_frame_path(app),
);
} else {
draw.to_frame(app, &frame).unwrap();
}
}
fn captured_frame_path(app: &App) -> std::path::PathBuf {
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join(format!("out_{:03}.svg", app.elapsed_frames()))
}
fn example_draw(app: &App) -> Draw {
// Begin drawing
let draw = app.draw();
// Clear the background to blue.
draw.background().color(CORNFLOWERBLUE);
// Draw a purple triangle in the top left half of the window.
let win = app.window_rect();
draw.tri()
.points(win.bottom_left(), win.top_left(), win.top_right())
.color(VIOLET);
// Draw an ellipse to follow the mouse.
let t = app.time;
draw.ellipse()
.x_y(app.mouse.x * t.cos(), app.mouse.y)
.radius(win.w() * 0.125 * t.sin())
.color(RED);
// Draw a line!
draw.line()
.weight(10.0 + (t.sin() * 0.5 + 0.5) * 90.0)
.caps_round()
.color(PALEGOLDENROD)
.points(win.top_left() * t.sin(), win.bottom_right() * t.cos());
// Draw a quad that follows the inverse of the ellipse.
draw.quad()
.x_y(-app.mouse.x, app.mouse.y)
.color(DARKGREEN)
.rotate(t);
// Draw a rect that follows a different inverse of the ellipse.
draw.rect()
.x_y(app.mouse.y, app.mouse.x)
.w(app.mouse.x * 0.25)
.hsv(t, 1.0, 1.0);
draw
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment