winit
winit copied to clipboard
How to implement a full frame rate animation?
I want to implement an animation that will run at 60 fps on my computer. But it's not a good idea to call request_redraw() directly on Event::RedrawEventsCleared and set control_flow to ControlFlow::Poll, which will run as many times as possible instead of matching the frame rate supported by my device. This consumes a lot of CPU.
Maybe control over rendering frequency is not a part of winit? Is there another crate or API I can use to control the rendering frequency?
I'm also interested in this question
I think something like this is what you're supposed to do. However this doesn't work well for wasm.
match *control_flow {
ControlFlow::Exit => (),
_ => {
if let Some(window) = &window {
window.request_redraw();
}
let start_time = Instant::now();
let elapsed_time_millis =
Instant::now().duration_since(start_time).as_millis() as u64;
let wait_millis = match 1000 / TARGET_FPS >= elapsed_time_millis {
true => 1000 / TARGET_FPS - elapsed_time_millis,
false => 0,
};
let new_instant = start_time + std::time::Duration::from_millis(wait_millis);
*control_flow = ControlFlow::WaitUntil(new_instant);
}
}