Web Sys crate Import Error

I am trying to get started with wasm and game dev using Erin Smith book 'Game Development with Rust and WebAssembley' but i am having the error with web_sys i cannot import window function and getting

unresolved import `web_sys::window
no `window` in the root

in my code
NOTE: I have installed all packages and are current ones

use wasm_bindgen::prelude::*;
use web_sys::{HtmlCanvasElement, CanvasRenderingContext2d};
use web_sys::window;



#[wasm_bindgen(start)]
pub fn main_js() -> Result<(), JsValue> {
    // Get the canvas element from the DOM
    let window = web_sys::window().unwrap();
    let document = window.document().unwrap();
    let canvas = document
        .get_element_by_id("canvas")
        .unwrap()
        .dyn_into::<HtmlCanvasElement>()
        .unwrap();

    // Get the 2D rendering context for the canvas
    let context = canvas
        .get_context("2d")?
        .unwrap()
        .dyn_into::<CanvasRenderingContext2d>()
        .unwrap();

    // Draw a rectangle on the canvas
    context.begin_path();
    context.rect(10.0, 10.0, 50.0, 50.0);
    context.stroke();

    Ok(())
}

How are you running the WebAssembly code? NodeJS doesn't have a global window object, so web_sys::window() will fail - the possibility of failure is why it returns an Option<web_sys::Window> instead of directly giving you the web_sys::Window.

1 Like

Yes i am using nodejs. I started my project using npm init rust-webpack. How do i go about the issue

nodejs doesn't have a DOM. You need a web browser to run the code in the OP.

Node.js is needed to compile your project, but as other posters have pointed out, you need to run the compiled WASM file in your web browser.

Since you are using rust-webpack, you should be able to run the following command in your project root folder: npm run start.

This will compile your project and open a browser window to http://localhost:8080 where you can view your finished webpage. If the browser window doesn't open automatically, check the output from NPM to confirm the port number, and open a tab yourself.

Also, it looks like your code makes use of an HTML canvas, so make sure that:

  1. In Cargo.toml, you have enabled the "Window", "Document", "CanvasRenderingContext2d" and "HtmlCanvasElement" features under [dependencies.web-sys]
  2. Make sure there is a <canvas id="canvas"></canvas> element in static/index.html
1 Like

Thanks in advance for the clarification. Now I am understanding some additional details I need to add to my code.