Skip to content

警告

只有 Rust 支持将 Slint 与 WebAssembly 一起使用。

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

使用 cargo 安装 wasm-pack

Terminal window

bash
cargo install wasm-pack

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

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

'cfg(target_arch = "wasm32")' 确保这些依赖项仅在为 wasm32 架构编译时激活。请注意,现在 rand 依赖项被重复了,以启用 "wasm-bindgen" 功能。

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

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

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

你还需要通过将 wasm_bindgen(start) 属性添加到 main 函数并使用 pub 关键字导出它来更改 main.rs

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

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

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

html
<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>

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

Terminal window

bash
python3 -m http.server

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

基于 MIT 协议发布