use std::num::NonZeroU32; use std::rc::Rc; use winit::event::{ElementState, Event, KeyEvent, WindowEvent}; use winit::event_loop::{ControlFlow, EventLoop}; use winit::keyboard::{KeyCode, PhysicalKey}; use winit::window::WindowBuilder; fn redraw(buffer: &mut [u32], width: usize, height: usize, flag: bool) { for y in 0..height { for x in 0..width { let value = if flag && x >= 100 && x < width - 100 && y >= 100 && y < height - 100 { 0x00ffffff } else { let red = (x & 0xff) ^ (y & 0xff); let green = (x & 0x7f) ^ (y & 0x7f); let blue = (x & 0x3f) ^ (y & 0x3f); (blue | (green << 8) | (red << 16)) as u32 }; buffer[y * width + x] = value; } } } fn main() { let event_loop = EventLoop::new().unwrap(); let window = Rc::new( WindowBuilder::new() .with_title("Press space to show/hide a rectangle") .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()) .unwrap(); } let context = softbuffer::Context::new(window.clone()).unwrap(); let mut surface = softbuffer::Surface::new(&context, window.clone()).unwrap(); let mut flag = false; event_loop .run(move |event, elwt| { elwt.set_control_flow(ControlFlow::Wait); match event { Event::WindowEvent { window_id, event: WindowEvent::RedrawRequested, } if window_id == window.id() => { // Grab the window's client area dimensions if let (Some(width), Some(height)) = { let size = window.inner_size(); (NonZeroU32::new(size.width), NonZeroU32::new(size.height)) } { // Resize surface if needed surface.resize(width, height).unwrap(); // Draw something in the window let mut buffer = surface.buffer_mut().unwrap(); redraw( &mut buffer, width.get() as usize, height.get() as usize, flag, ); buffer.present().unwrap(); } } Event::WindowEvent { event: WindowEvent::CloseRequested, window_id, } if window_id == window.id() => { elwt.exit(); } Event::WindowEvent { event: WindowEvent::KeyboardInput { event: KeyEvent { state: ElementState::Pressed, physical_key: PhysicalKey::Code(KeyCode::Space), .. }, .. }, window_id, } if window_id == window.id() => { // Flip the rectangle flag and request a redraw to show the changed image flag = !flag; window.request_redraw(); } _ => {} } }) .unwrap(); }