项目初始化
要求需要先安装好 Node.js,和 Rust 环境。
- 建一个新的文件夹,将工作目录切换到该目录下
npm init rust-webpack
如果能看到下面的图案就是成功了:
🦀 Rust + 🕸 WebAssembly + Webpack = ❤
- 安装依赖
npm install
- 安装 wasm-pack
Linux 和 Mac OSX 的操作系统可以使用 cURL 进行安装:
curl https://rustwasm.github.io/wasm-pack/installer/init . sh -sSf | sh
Windows 可以下载单独的 exe,进行安装:下载地址
- 运行服务器
npm run start
会自动安装 Rust 所需的依赖包,如果成功的话,开发者工具中终端界面可以看到 Hello, World
- 更新 Rust 版本
目前模板的 Rust 版本为 2018
(2022年7月5日时),在 cargo.toml
将版本改成 2021
:
edition = "2021"
- 更新依赖的版本
cargo.toml
中的依赖也不是最新的,可以更新到新的版本。
Visusal Studio Code 中有 Crates 插件,可以获取依赖的版本信息。
[dev-dependencies]
wasm-bindgen-test = "0.3.31"
futures = "0.3.21"
js-sys = "0.3.22"
wasm-bindgen-futures = "0.4.31"
- 更新
console_error_panic_hook
这是个非常有用的库,一看名字就知道是用来 Debug 的,目前最新是 0.1.7
。
[target."cfg(debug_assertions)".dependencies]
console_error_panic_hook = "0.1.7"
绘制图形到 Canvas
可以使用 <canvas>
将图形绘制到浏览器窗口中,在 static\index.html
中 <body>
后添加 <canvas>
:
<body>
<canvas id="canvas" tabindex="0" height="600" width="600">Your browser does not support the canvas.</canvas>
<!-- ... 不要删除后面的 <script> ... -->
终于到了写 Rust 代码的时候了!
在 lib.rs
引入依赖
use wasm_bindgen::JsCast;
原有代码里的 #[cfg(debug_assertions)]
可以删除。
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::console;
// When the `wee_alloc` feature is enabled, this uses `wee_alloc` as the global
// allocator.
//
// If you don't want to use `wee_alloc`, you can safely delete this.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
// This is like the `main` function, except for JavaScript.
#[wasm_bindgen(start)]
pub fn main_js() -> Result<()