I'm trying to use glfw, gl to draw a line on a window. But i don't know why it not works.
Cargo.toml
[dependencies]
gl = "0.14.0"
glfw = "0.58.0"
main.rs
use gl;
use gl::types;
use gl::types::{GLchar, GLsizeiptr};
use glfw::{Context, Key, WindowHint, Action};
fn main() {
let mut glfw = glfw::init(glfw::fail_on_errors).unwrap();
// glfw.window_hint(WindowHint::Resizable(false));
lfw.window_hint(WindowHint::TransparentFramebuffer(true));
glfw.window_hint(WindowHint::Resizable(false));
glfw.window_hint(WindowHint::Decorated(false));
glfw.window_hint(WindowHint::DoubleBuffer(true));
glfw.window_hint(WindowHint::Floating(true));
glfw.window_hint(WindowHint::Samples(Some(4)));
let (mut window, events) = glfw.create_window(300, 300, "Hello this is window", glfw::WindowMode::Windowed)
.expect("Failed to create GLFW window.");
window.set_key_polling(true);
window.set_pos(100, 100);
window.make_current();
gl::load_with(|s| {window.get_proc_address(s) as *const std::os::raw::c_void});
while !window.should_close() {
glfw.poll_events();
for (_, event) in glfw::flush_messages(&events) {
handle_window_event(&mut window, event);
}
println!("---------------------draw-------------");
draw_line(&mut window);
}
}
fn handle_window_event(window: &mut glfw::Window, event: glfw::WindowEvent) {
match event {
glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => {
window.set_should_close(true)
}
_ => {}
}
}
fn draw_line(window: &mut glfw::Window) {
let vertices: [f32; 6] = [
0.5, 0.0, 0.0, // Start point (X, Y, Z)
300.0, 300.0, 0.0, // End point (X, Y, Z)
];
let mut vao = 0;
let mut vbo = 0;
unsafe {
gl::GenVertexArrays(1, &mut vao);
gl::GenBuffers(1, &mut vbo);
gl::BindVertexArray(vao);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::BufferData(
gl::ARRAY_BUFFER,
(vertices.len() * std::mem::size_of::()) as GLsizeiptr,
vertices.as_ptr() as *const std::os::raw::c_void,
gl::STATIC_DRAW,
);
gl::VertexAttribPointer(
0,
3,
gl::FLOAT,
gl::FALSE,
(3 * std::mem::size_of::()) as i32,
std::ptr::null(),
);
gl::EnableVertexAttribArray(0);
gl::BindBuffer(gl::ARRAY_BUFFER, 0);
gl::BindVertexArray(0);
gl::UseProgram(0);
let color_location = gl::GetUniformLocation(0, "red".as_ptr() as *const GLchar );
gl::Uniform4f(color_location, 1.0, 0.0, 0.0, 1.0);
gl::BindVertexArray(vao);
gl::DrawArrays(gl::LINES, 0, 2);
}
window.swap_buffers();
}
rust 1.98.0 mac os 12.7.6 rustover 2026.2.2
Using glfw + gl to create a openGL window, the window's background is transparence and has no titlebar.
As you see, then function `draw_line` seems not work, and the function body code is searched result by google.
Please help me check where the problem lies in the code and why the drawn line is not displayed.