Skip to content

在浏览器中运行

如果你使用 Rust,本教程到目前为止一直用 cargo run 将代码作为原生应用构建和运行。 原生应用是 Slint 框架的主要目标,但它也支持 WebAssembly。 本节使用标准 Rust 工具 wasm-bindgen 和 wasm-pack 在浏览器中运行游戏。 阅读 wasm-bindgen 文档 以了解更多关于使用 wasm 和 rust 的内容。

使用 cargo 安装 wasm-pack:

Terminal window
cargo install wasm-pack
bash

编辑 Cargo.toml 文件以添加依赖。

[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen = { version = "0.2" }
getrandom = { version = "0.3.4", features = ["wasm_js"] }
toml

'cfg(target_arch = "wasm32")' 确保这些依赖仅在 为 wasm32 架构编译时生效。请注意,getrandom 配置了 "wasm_js" 特性,这是在 wasm32 目标上生成随机数所必需的。

在你编辑 Cargo.toml 的同时,做最后一处修改。通过添加以下内容将二进制文件 转换为库:

[lib]
path = "src/main.rs"
crate-type = ["cdylib"]
toml

这是因为 wasm-pack 要求 Rust 生成一个 "cdylib"。

你还需要修改 main.rs,为 main 函数添加 wasm_bindgen(start) 属性,并使用 pub 关键字导出它:

#[cfg_attr(target_arch = "wasm32",
wasm_bindgen::prelude::wasm_bindgen(start))]
pub fn main() {
//...
}
rust

使用 wasm-pack build --release --target web 编译程序。这会 创建一个 pkg 目录,其中包含若干文件,包括一个以程序名命名的 .js 文件, 你需要将它导入到 HTML 文件中。

在项目的顶层创建一个最小的 index.html,它声明一个用于渲染的 <canvas> 元素,并加载生成的 wasm 文件。Slint 运行时要求 <canvas> 元素的 id 为 id = "canvas"。 (将 memory.js 替换为正确的文件名)。

<html>
<body>
<!-- canvas required by the Slint runtime -->
<canvas id="canvas"></canvas>
<script type="module">
// import the generated file.
import init from './pkg/memory.js';
init();
</script>
</body>
</html>
html

遗憾的是,通过 file:// URL 访问时,文件系统上的文件不允许加载 ES 模块, 因此你无法直接加载 index.html。你需要通过 Web 服务器来提供它。 例如,使用 Python,运行:

Terminal window
python3 -m http.server
bash

现在你可以在 http://localhost:8000 访问游戏。


© 2026 SixtyFPS GmbH