rust webassembly hello world

依赖安装

1
2
cargo install wasm-pack
cargo install cargo-generate

使用模板创建

1
cargo generate --git https://github.com/rustwasm/wasm-pack-template

构建

1
wasm-pack build --target web

js调用

pkg 文件夹下新建 index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!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>测试调用</title>
</head>

<body>
<script type="module">
import initSync, { greet } from './wchar_wasm_helloworld.js';
await initSync();
greet();
</script>
</body>

</html>

案例一

我们来调用写个方法调用,添加如下方法

1
2
3
4
#[wasm_bindgen]
pub fn example_one(v :i32) -> i32 {
return v *2;
}

重新编译下

1
wasm-pack build --target web

修改js如下

1
2
3
4
5
6
<script type="module">
import initSync, { greet,example_one } from './wchar_wasm_helloworld.js';
await initSync();
//greet();
alert(example_one(30));
</script>

运行结果

案例二 DOM操作

Cargo.toml 中添加

1
2
3
4
5
6
7
8
9
10
11
[dependencies.web-sys]
version = "0.3.64"
features = [
'Document',
'Element',
'HtmlElement',
'Node',
'Window',
'CanvasRenderingContext2d',
'HtmlCanvasElement'
]

lib.rs 中添加以下方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

/**
* window.onload
* 创建一个 h1 元素
*/
#[wasm_bindgen(start)]
fn run() -> Result<(), JsValue> {
let window = web_sys::window().expect("no global `window` exists");
let document = window.document().expect("should have a document on window");
let body = document.body().expect("document should have a body");
let val = document.create_element("h1")?;
val.set_text_content(Some("Hello from Rust!"));
body.append_child(&val)?;
Ok(())
}

刷新页面即可预览

案例三 canvas操作

lib.rs 中添加以下方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 画个笑脸
*/
#[wasm_bindgen]
pub fn smiling_face() {
let document = web_sys::window().unwrap().document().unwrap();
let canvas = document.get_element_by_id("canvas").unwrap();
let canvas: web_sys::HtmlCanvasElement = canvas
.dyn_into::<web_sys::HtmlCanvasElement>()
.map_err(|_| ())
.unwrap();

let context = canvas
.get_context("2d")
.unwrap()
.unwrap()
.dyn_into::<web_sys::CanvasRenderingContext2d>()
.unwrap();

context.begin_path();

// Draw the outer circle.
context
.arc(75.0, 75.0, 50.0, 0.0, std::f64::consts::PI * 2.0)
.unwrap();

// Draw the mouth.
context.move_to(110.0, 75.0);
context.arc(75.0, 75.0, 35.0, 0.0, std::f64::consts::PI).unwrap();

// Draw the left eye.
context.move_to(65.0, 65.0);
context
.arc(60.0, 65.0, 5.0, 0.0, std::f64::consts::PI * 2.0)
.unwrap();

// Draw the right eye.
context.move_to(95.0, 65.0);
context
.arc(90.0, 65.0, 5.0, 0.0, std::f64::consts::PI * 2.0)
.unwrap();

context.stroke();
}

修改 index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!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>测试调用</title>
</head>
<body>
<canvas id="canvas"></div>
<script type="module">
import initSync, { greet,example_one,smiling_face } from './wchar_wasm_helloworld.js';
await initSync();
//greet();
//alert(example_one(30));
smiling_face();
</script>
</body>
</html>

刷新页面预览

本章代码

https://github.com/wchar-net/rust-webassembly-helloworld

rustwasm 教程书籍

https://rustwasm.github.io/wasm-bindgen/introduction.html