softbuffer/examples/winit.rs
Liam Murphy d735510f72 Add web support
A limitation of this implementation is that it can't coexist with anything which creates a canvas context other than `CanvasRenderingContext2D`, since only one context can exist per canvas.
2022-02-12 20:24:18 +11:00

60 lines
1.9 KiB
Rust

use softbuffer::GraphicsContext;
use winit::event::{Event, WindowEvent};
use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::WindowBuilder;
fn main() {
let event_loop = EventLoop::new();
let window = WindowBuilder::new().build(&event_loop).unwrap();
#[cfg(target_arch = "wasm32")]
{
use winit::platform::web::WindowExtWebSys;
web_sys::window()
.unwrap()
.document()
.unwrap()
.body()
.unwrap()
.append_child(&window.canvas())
.unwrap();
}
let mut graphics_context = unsafe { GraphicsContext::new(window) }.unwrap();
event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Wait;
match event {
Event::RedrawRequested(window_id) if window_id == graphics_context.window().id() => {
let (width, height) = {
let size = graphics_context.window().inner_size();
(size.width, size.height)
};
let buffer = (0..((width * height) as usize))
.map(|index| {
let y = index / (width as usize);
let x = index % (width as usize);
let red = x % 255;
let green = y % 255;
let blue = (x * y) % 255;
let color = blue | (green << 8) | (red << 16);
color as u32
})
.collect::<Vec<_>>();
graphics_context.set_buffer(&buffer, width as u16, height as u16);
}
Event::WindowEvent {
event: WindowEvent::CloseRequested,
window_id,
} if window_id == graphics_context.window().id() => {
*control_flow = ControlFlow::Exit;
}
_ => {}
}
});
}