Search code examples
canvasrustgraphicssdlsdl-2

Getting pixels of many different colors when drawing with SDL in Rust


I am playing around SDL2 in Rust and want to draw a rectangle and a point on the screen. While this does seem to function to an extent, I get all sorts of trash pixels of varying colors surrounding the areas where the desired artifact has been drawn. Why is this? I'm on a MacBook Pro with an M1 Max if that helps.

screenshot of the issue

Here's the code:

extern crate sdl2;

use sdl2::event::Event;
use sdl2::pixels::Color;
use sdl2::rect::Point;
use sdl2::rect::Rect;

pub fn main() {
    let sdl_context = sdl2::init().unwrap();
    let video_subsystem = sdl_context.video().unwrap();

    let window = video_subsystem
        .window("rust-sdl2 demo", 800, 600)
        .position_centered()
        .build()
        .unwrap();

    let mut canvas = window.into_canvas().build().unwrap();
    canvas.set_draw_color(Color::RGB(255, 255, 255));
    let point = Point::new(400, 400);
    canvas.draw_point(point).unwrap();
    canvas.fill_rect(Rect::new(10, 10, 80, 70)).unwrap();
    canvas.present();

    let mut event_pump = sdl_context.event_pump().unwrap();
    'running: loop {
        for event in event_pump.poll_iter() {
            match event {
                Event::Quit { .. } => break 'running,
                _ => {}
            }
        }
    }
}


Solution

  • You need to clear the canvas, clearing the canvas at the start of the frame is normal to ensure there aren't any artefacts from previous frames left over, or from something else leftover (i.e another program that previously used that memory and didn't zero it out before exiting/ moving on). In your case you'd need to add

    // Adust the color to whatever you want
    canvas.set_draw_color(Color::RGB(0, 0, 0));
    canvas.clear();
    

    Right after the let mut canvas = ... line but before drawing anything on to the canvas


    Not doing this combined with not painting to every pixel on screen for every frame leads to a very distinct visual, if you're familiar with Source engine games (Half Life, CS:GO, Portal etc.) and have ever been out of bounds in one of those games you'll know what I'm talking about, it's the "Hall of Mirrors effect". This Q&A on the Gamedev Stack Exchange has some more information on why it happens, and here's a video showcasing the effect in the original Doom