如何将我的WebAssembly导入nextjs

问题描述 投票:0回答:1

enter image description here

如图所示,我将 pkg 的内容复制到公共 nextjs 项目文件夹中。 nextjs 应用程序在我的 rust lib 项目中初始化。

[package]
name = "chess"
version = "0.1.0"
edition = "2021"

[lib]
crate-type=["cdylib"]

[dependencies]
wasm-bindgen="0.2"
js-sys="0.3.45"

[dependencies.web-sys]
version = "0.3.69"
features = [
    "Window",
    "Document",
    "HtmlCanvasElement",
    "CanvasRenderingContext2d",
    "Element",
    "Node",
    "Event",
    "MouseEvent"
]
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub struct Board{
    width: i32,
    height: i32,
}

#[wasm_bindgen]
impl Board {
    pub fn init(x: i32, y: i32) -> Board {
        Board {
            width: x,
            height: y,
        }
    }

    pub fn draw(&self, canvas: web_sys::CanvasRenderingContext2d) {
        canvas.set_fill_style(&JsValue::from_str("black"));
        canvas.set_stroke_style(&JsValue::from_str("white"));
        let size: f64 = 64.0;
        for i in 0..self.width {
            for j in 0..self.height {
                let x: f64 = i as f64;
                let y: f64 = j as f64;
                canvas.fill_rect(x*size, y*size, size, size);
                canvas.stroke_rect(x*size-5.0, y*size-5.0, size-10.0, size-10.0);
            }    
        }
    }
}

我打算做的是使用 Board 结构来初始化并在我的画布上绘制一个板

// Get the canvas element and its 2D context
    const canvas = document.getElementById('canvas');
    const context = canvas.getContext('2d');

    // Create a new instance of the Board with width 10 and height 10
    const board = Board.init(10, 10);

    // Call the draw method on the Board instance to draw the grid
    board.draw(context);

但我似乎找不到使用 wasm-pack build 生成的文件的方法

next.js rust webassembly
1个回答
0
投票

注意

package.json
文件夹中的
/pkg
文件。运行
npm install ./pkg
,然后尝试运行它。这将允许您直接使用类型导入 WASM 二进制文件,而不是获取它...

© www.soinside.com 2019 - 2024. All rights reserved.