Web Integration

To run our Rust code in the browser, we need a simple HTML page to load the compiled WebAssembly module and a build script to automate the process.

1. HTML Entry Point

Create index.html in the project root. This file provides the canvas element that window.rs looks for and loads the WASM file generated by wasm-pack.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Unreal Majid - GPU Particles</title>
    <style>
        * {
            padding: 0;
            margin: 0;
            overflow: hidden; /* Prevent scrollbars */
        }

        canvas {
            background-color: black;
            width: 100vw;
            height: 100vh;
            display: block;
        }
    </style>
</head>

<body id="wasm-example">
    <!-- The canvas ID must match what we defined in window.rs -->
    <canvas id="canvas"></canvas>
    
    <script type="module">
        // Import the WASM module wrapper generated by wasm-pack
        import init from "./pkg/Unreal_Majid.js";
        
        // Initialize the WASM module
        init().then(() => {
            console.log("WASM Loaded & Started");
        });
    </script>
</body>
</html>
📝 Note

The path ./pkg/Unreal_Majid.js points to the folder created by wasm-pack. We will generate this in the next step.

2. Automation with Makefile

Create a Makefile to simplify building for both targets (Native and Web). This saves us from typing long commands repeatedly.

SRCS=  src/lib.rs  src/main.rs  src/core/entry_point.rs  src/core/mod.rs  src/core/renderer.rs	src/core/window.rs
CFLAGS= --release
CPP= cargo
NAME= particle-system

.PHONY: clean

# Default target: Build release binary
all: ./target/release/$(NAME)

# Build both native binary and WASM package
./target/release/$(NAME): $(SRCS)
	$(CPP) build $(CFLAGS)
	wasm-pack build --target web --release --out-name Unreal_Majid

clean:
	rm -rf target/release/build

fclean: clean
	rm -rf ./target/release/$(NAME)
	rm -rf pkg/

re: fclean all

How to use it

  • Run make to build everything.
  • Run make re to clean and rebuild from scratch.