Until now, to see what we drew, we had to run the program and then open a file. This chapter changes that: we open a real window and show our canvas in it.

The drawing itself barely changes. What changes is the structure of the program. Instead of drawing once and stopping, it will run in a loop, redraw the image dozens of times per second and react to the keyboard. That loop is what will let us draw with the mouse in the next chapter.
Adding a dependency#
Opening a window means talking to the operating system, and each system has its own way of doing it: Windows, macOS and Linux have nothing in common at that level. That kind of work is beyond the scope of this tutorial; it would fit better in a future course on systems programming. So we'll use a library, what Rust calls a crate.
Crates published by the community are on crates.io. The one we'll use is called minifb, for "mini framebuffer". It does exactly what we need and not much more: open a window, show an array of pixels in it, and tell us what the keyboard and mouse are doing. And it expects pixels in exactly the 0x00RRGGBB format, one u32 per pixel, the same as our canvas.
To add it to the project:
cargo add minifb@0.29.0The @0.29.0 pins the version. Without it, Cargo would take the latest one, which might have changed since this tutorial was written. With it, you're sure to have exactly the same one as me.
The command added a line to Cargo.toml:
[dependencies]
minifb = "0.29.0"It also filled in Cargo.lock, which was almost empty until now. minifb itself depends on other crates, which depend on other crates, and Cargo.lock records the exact version of each one. You don't need to edit it, but keep it in git: it's what guarantees the project will build the same way on another machine.
The first build will take longer than usual, while Cargo downloads and compiles all these dependencies. The next ones will be fast, it only recompiles what changed.
The documentation of every crate is generated automatically and published on docs.rs. Get into the habit of taking a look: you'll find every available function there, with its parameters and often an example.
The size of the window#
The width and height of the window will be used in several places. Rather than writing 1080 and 720 everywhere, we put them in constants, in a new file src/config.rs:
pub const WIDTH: usize = 1080;
pub const HEIGHT: usize = 720;Unlike let, a constant must always have its type written out. By convention, its name is in uppercase.
Opening the window#
Replace src/main.rs with this beginning:
mod canvas;
mod color;
mod config;
mod image;
#[allow(dead_code)] // Vec2 comes back in chapter 5.
mod vec2;
use minifb::{Key, KeyRepeat, Window, WindowOptions};
use canvas::Canvas;
use color::{WHITE, rgb_to_u32};
use config::{HEIGHT, WIDTH};
use image::Image;
fn main() {
let mut window = Window::new("Paint", WIDTH, HEIGHT, WindowOptions::default())
.expect("could not open the window");
// ...
}use minifb::{...} imports what we need from the crate, exactly as we import from our own modules. For an external crate, you write its name directly, without crate::.
Window::new takes the window title, its size, and some options. WindowOptions::default() gives the default options, which suit us fine. Opening a window can fail (no screen, no display server…), so Window::new returns a Result. The .expect(...) says: if it's an error, stop the program with this message.
The render loop#
Here's the heart of the program. It replaces the // ...:
let mut canvas = Canvas::new(WIDTH, HEIGHT);
while window.is_open() && !window.is_key_down(Key::Escape) {
// Each frame, we clear the canvas and draw everything again.
canvas.clear(WHITE);
canvas.fill_rect(100, 100, 240, 160, rgb_to_u32(220, 50, 50));
canvas.fill_circle(600, 250, 120, rgb_to_u32(50, 120, 220));
canvas.draw_line(50, 650, 1030, 400, rgb_to_u32(0, 0, 0));
window
.update_with_buffer(&canvas.pixels, WIDTH, HEIGHT)
.expect("could not update the window");
}The loop runs as long as the window is open and the Escape key isn't pressed. Each pass through the loop produces one image, what we call a frame. By default, minifb runs the loop at 250 frames per second at most.
At each frame, we clear the canvas, redraw everything, then update_with_buffer sends our pixels to the window. That same function also takes care of collecting what happened since the previous frame: keys pressed, mouse movements, a click on the close button. It's thanks to it that is_open and is_key_down give up-to-date answers on the next pass.
Redrawing an image that doesn't move dozens of times per second may seem pointless, and here, it kind of is. But from the next chapter on, the image will change with the mouse, and this will be the simplest way to always show the right state: we don't ask ourselves what changed, we redraw everything. For an image this size, it's no problem at all performance-wise.
A screenshot#
We still have the code that writes PPM files, it would be a shame not to use it anymore. We'll save the content of the window when you press S. Add this inside the loop, right before update_with_buffer:
if window.is_key_pressed(Key::S, KeyRepeat::No) {
// ...
}is_key_pressed returns true only on the frame where the key has just been pressed. KeyRepeat::No says we don't want automatic repetition if you hold it down, like when you hold a letter in a word processor.
Solution
if window.is_key_pressed(Key::S, KeyRepeat::No) {
match Image::from_canvas(&canvas).save_ppm("screenshot.ppm") {
Ok(()) => println!("saved to screenshot.ppm"),
Err(e) => eprintln!("could not save the image: {e}"),
}
}With this match, a saving error doesn't stop the program: we print the problem and the window stays open. That's the difference with the expect of Window::new.
Running it#
Here's the full main.rs:
mod canvas;
mod color;
mod config;
mod image;
#[allow(dead_code)] // Vec2 comes back in chapter 5.
mod vec2;
use minifb::{Key, KeyRepeat, Window, WindowOptions};
use canvas::Canvas;
use color::{WHITE, rgb_to_u32};
use config::{HEIGHT, WIDTH};
use image::Image;
fn main() {
let mut window = Window::new("Paint", WIDTH, HEIGHT, WindowOptions::default())
.expect("could not open the window");
let mut canvas = Canvas::new(WIDTH, HEIGHT);
while window.is_open() && !window.is_key_down(Key::Escape) {
// Each frame, we clear the canvas and draw everything again.
canvas.clear(WHITE);
canvas.fill_rect(100, 100, 240, 160, rgb_to_u32(220, 50, 50));
canvas.fill_circle(600, 250, 120, rgb_to_u32(50, 120, 220));
canvas.draw_line(50, 650, 1030, 400, rgb_to_u32(0, 0, 0));
if window.is_key_pressed(Key::S, KeyRepeat::No) {
match Image::from_canvas(&canvas).save_ppm("screenshot.ppm") {
Ok(()) => println!("saved to screenshot.ppm"),
Err(e) => eprintln!("could not save the image: {e}"),
}
}
window
.update_with_buffer(&canvas.pixels, WIDTH, HEIGHT)
.expect("could not update the window");
}
}cargo runA 1080 × 720 window opens, with a red rectangle, a blue disc and a black line. The terminal stays quiet. Press S, and it prints:
saved to screenshot.ppmThe file screenshot.ppm contains exactly what the window shows. Close the window or press Escape to quit.
Exercises#
-
Make the red square bounce off the edges of the window. You need its position and its speed in variables declared before the loop, which you update at each frame. When it hits an edge, flip the speed in that direction.
-
Move the blue disc with the arrow keys. This time, we want it to keep moving as long as the key is held:
is_key_downis the right function. The arrows are calledKey::Left,Key::Right,Key::UpandKey::Down. -
Bonus: each time B is pressed, change the background color to the next one in a list of colors, and go back to the first after the last.
Solutions
1. The position and speed are declared with let mut before the loop, so they survive from one frame to the next:
let (mut x, mut y) = (100, 100);
let (mut vx, mut vy) = (2, 1);
let size = 60;
while window.is_open() && !window.is_key_down(Key::Escape) {
x += vx;
y += vy;
if x <= 0 || x + size >= WIDTH as i32 {
vx = -vx;
}
if y <= 0 || y + size >= HEIGHT as i32 {
vy = -vy;
}
canvas.clear(WHITE);
canvas.fill_rect(x as usize, y as usize, size as usize, size as usize, rgb_to_u32(220, 50, 50));
// ...
}x, y and the speed are i32, because the speed becomes negative when the square heads back the other way. We only convert them to usize when drawing, since that's what fill_rect expects. The loop runs fast, at 250 frames per second: a speed of 2 pixels per frame is already 500 pixels per second.
2. We test each arrow, and move the center by a few pixels on each frame where it's held:
let (mut cx, mut cy) = (600, 250);
while window.is_open() && !window.is_key_down(Key::Escape) {
let speed = 2;
if window.is_key_down(Key::Left) {
cx -= speed;
}
if window.is_key_down(Key::Right) {
cx += speed;
}
if window.is_key_down(Key::Up) {
cy -= speed;
}
if window.is_key_down(Key::Down) {
cy += speed;
}
canvas.clear(WHITE);
canvas.fill_circle(cx as usize, cy as usize, 120, rgb_to_u32(50, 120, 220));
// ...
}The top of the window is y = 0: to go up, we decrease y. As in exercise 1, the position is an i32 for the calculations and converted to usize for drawing.
3. An array of colors and an index. The % (remainder of the division) brings the index back to 0 after the last element:
let backgrounds = [WHITE, rgb_to_u32(255, 240, 200), rgb_to_u32(200, 230, 255)];
let mut current = 0;
while window.is_open() && !window.is_key_down(Key::Escape) {
if window.is_key_pressed(Key::B, KeyRepeat::No) {
current = (current + 1) % backgrounds.len();
}
canvas.clear(backgrounds[current]);
// ...
}Recap#
- A crate is a Rust library. You add it with
cargo add, preferably pinning the version, andCargo.lockfreezes the versions of all the dependencies. - The documentation of every crate is on docs.rs.
expectstops the program if aResultis an error. We keep it for errors we can't recover from, and usematchfor the others.- A graphical app runs in a loop: at each frame, we read the input, redraw everything, and display it.
is_key_downis true as long as the key is held,is_key_pressedonly once per press.
In chapter 5, the mouse comes into play: we click, we drag, and a rectangle appears before our eyes.