使用 Rust 与 WebAssembly 进行图形开发

项目初始化

要求需要先安装好 Node.js,和 Rust 环境。

  1. 建一个新的文件夹,将工作目录切换到该目录下
npm init rust-webpack

如果能看到下面的图案就是成功了:

🦀 Rust + 🕸 WebAssembly + Webpack = ❤
  1. 安装依赖
npm install
  1. 安装 wasm-pack

Linux 和 Mac OSX 的操作系统可以使用 cURL 进行安装:

curl https://rustwasm.github.io/wasm-pack/installer/init . sh -sSf | sh

Windows 可以下载单独的 exe,进行安装:下载地址

  1. 运行服务器
npm run start

会自动安装 Rust 所需的依赖包,如果成功的话,开发者工具中终端界面可以看到 Hello, World

Hello, World

  1. 更新 Rust 版本

目前模板的 Rust 版本为 2018(2022年7月5日时),在 cargo.toml 将版本改成 2021

edition = "2021"
  1. 更新依赖的版本

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"
  1. 更新 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<()
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值