#web-api #web-apps #canvas #context #wrapper #zero #canvas-rendering-context2-d

js-canvas-rendering-context-2d

一个旨在成为 CanvasRenderingContext2D Web API 零依赖封装库,用于 WASM Rust 应用程序

4 个版本 (2 个破坏性更新)

0.3.0 2022 年 4 月 24 日
0.2.0 2022 年 3 月 13 日
0.1.1 2022 年 3 月 4 日
0.1.0 2022 年 3 月 4 日

#1096 in WebAssembly

自定义许可

2.5MB
432

包含 (WOFF 字体, 680KB) doc/NanumBarunGothic.ttf.woff, (WOFF 字体, 400KB) doc/NanumBarunGothic.ttf.woff2, (WOFF 字体, 190KB) doc/FiraSans-Medium.woff, (WOFF 字体, 135KB) doc/FiraSans-Medium.woff2, (WOFF 字体, 185KB) doc/FiraSans-Regular.woff, (WOFF 字体, 130KB) doc/FiraSans-Regular.woff2 以及更多

JS-CANVAS-RENDERING-CONTEXT-2D

CanvasRenderingContext2D 封装器

此库旨在成为用于 WASM Rust 应用程序的 CanvasRenderingContext2D Web API 的零依赖封装。

使用此库的 Rust 程序可以绑定 DOM 中的单个 canvas 元素,并使用库中的函数来控制该 canvas 的上下文。

此仓库还包括文件 rust.wasm.canvasrenderingcontext2d.js。要在网页上使用此库,请将 .js 文件加载到页面中,然后调用

// reference the context manager for ease of calls. You will have one manager per webpage. It can contain contexts for multiple canvases on that page.
let manager = rust.wasm.canvasRenderingContext2DManager;

// callback that is called once the canvas element is bound to the wasm program
let initCallback = function(result) {
    // you probably want to call the rust program's main function here 
    result.instance.exports.main();
};

// callback that is called on window resize
let resizeCallback = function(result) {
    // you may want to redraw when the window is resized
    result.instance.export.draw();
}

// callback that is called on the browsers' request animation frame
let animateCallback = function(result) {
    // you may want to tick the program and re-draw here
    result.instance.export.tick();
    result.instance.export.draw();
}

let callbacks = {
    onInit: initCallback,
    onResize: resizeCallback,
    onAnimate: animateCallback
};

// create a context from the manager
let localContext = manager.addContext(canvasId, wasmPath, callbacks);

// initing the context will bind the canvas element to the wasm program and then call the callback
localContext.init();

运行此仓库中的示例

此仓库中的示例包含一个网站,其中包含多个 canvas,它们都绑定到使用此库与 canvas 交互的 rust/wasm 程序。一旦您将仓库本地化,您需要执行以下操作才能运行它

  • 将 wasm32-unknown-unknown 添加为构建目标
    • 调用 rustup target add wasm32-unknown-unknown
  • 构建
    • 调用 cargo build --example * --target wasm32-unknown-unknown
  • 使用某种本地 Web 服务器查看示例
    • 为此,我喜欢使用 Ian Kettlewell 的 devserver。它提供本地 Web 服务器,该服务器侦听目录中的更改并将它们推出去。
    • 您可以从命令行运行 cargo install devserver 来安装 devserver
    • 要运行它,请打开一个新的命令行终端,并导航到仓库的目录。然后在终端中运行 devserver。您可以通过按 ctrl+c 来退出服务器。
    • 本地服务器启动后,在任何网页浏览器中访问 localhost:8080,您应该能看到示例。

无运行时依赖。