• Stars
    star
    170
  • Rank 223,357 (Top 5 %)
  • Language
    Rust
  • License
    Apache License 2.0
  • Created over 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JavaScript-WebAssembly interop library for Rust.

docs.rs docs

Make writing web applications using Rust WebAssembly easy

I wanted a library that someone could learn in an afternoon how to use and start making interactive browser experiences with. This project doesn't support every browser function under the sun. Though you can easily add your own using the runtime Javascript invoking mechanism used by this library. Feel free to submit a PR for more functionality.

  • async & coroutine support
  • element operations
  • mouse, keyboard, and change event listeners
  • canvas2d
  • localstorage
  • fetch & XMLHttpRequest
  • style & classes
  • history & location info
  • WebGPU
  • other utilities

Check out the documentation here

cargo add web

Hello World

Let's just look at a basic example of how to put things in the console:

use web::*;

fn main() {
    console_log("Hello, world!");
}
<html>
    <head>
        <meta charset="utf-8">
        <script src="https://unpkg.com/js-wasm/js-wasm.js"></script>
        <script type="application/wasm" src="helloworld.wasm"></script>
    </head>
    <body>
        Open my console.
    </body>
</html>

Remember to configure your library Cargo.toml for WebAssembly

# add these lines for WebAssembly to end of your Cargo.toml

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

[profile.release]
lto = true
cargo build --target wasm32-unknown-unknown --release
cp target/wasm32-unknown-unknown/release/helloworld.wasm .
python3 -m http.server

# open http://localhost:8000 in browser
# right click, inspect, look at message in console

Full example is here.

Something more advanced?

Let's look at our snake example and some of it's key feature usages:

Screen Shot 2022-12-21 at 12 35 48 PM

Play demo here

canvas

This example uses canvas

//get an element and get the 2D context for canvas
let screen = query_selector("#screen");
let width: f64 = get_property_f64(&screen, "width");
let height: f64 = get_property_f64(&screen, "height");
let ctx = CanvasContext::from_element(&screen);

...

//clear screen
self.ctx.clear_rect(
    0.0,
    0.0,
    self.canvas_width as f64,
    self.canvas_height as f64,
);

// iterate through all the cells of the screen and draw a rectangle
for (_id, (pos, color)) in &mut self.world.query::<(&Position, &Color)>() {
    self.ctx.set_fill_style(&color.0);
    self.ctx.fill_rect(
        (pos.0 * (self.canvas_width / MAP_WIDTH)) as f64,
        (pos.1 * (self.canvas_height / MAP_HEIGHT)) as f64,
        (self.canvas_width / MAP_WIDTH) as f64,
        (self.canvas_height / MAP_HEIGHT) as f64,
    );
}

request animation frame

Let's see how to run the game loop

fn game_loop() {
    // run game loop assuming 15 ms has passed
    match Game::instance().run(15.0) {
        Err(e) => console_error(&e.to_string()),
        _ => (),
    };
    // request next animation frame
    request_animation_frame(game_loop);
}

... 

// start the loop
request_animation_frame(game_loop);

events

let body = query_selector("body");
element_add_key_down_listener(&body, |e| {
    Game::instance().key_down(e.key_code as u32);
});

Async & Coroutines

This library has support for async and spawning coroutines. Consider this program that starts a looping console log and also draws random squares on a screen.

use web::*;

// easily make your first function async
#[web::main]
async fn main() {
    let canvas = query_selector("#canvas");
    let ctx = CanvasContext::from_element(&canvas);

    // we can spawn concurrent operations
    coroutine(async {
        loop {
            console_log("⏰ tik");
            // hand async set_timeout
            sleep(1000).await;
            console_log("⏰ tok");
            sleep(1000).await;
        }
    });

    loop {
        // draw a random color rect
        ctx.set_fill_style(&format!(
            "rgb({}, {}, {})",
            random() * 255.0,
            random() * 255.0,
            random() * 255.0
        ));
        ctx.fill_rect(
            random() * 500.0,
            random() * 500.0,
            random() * 500.0,
            random() * 500.0,
        );
        // a more async way to write graphics code
        wait_til_animation_frame().await;
    }
}

License

This project is licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in web by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

More Repositories

1

tour_of_rust

A tour of rust's language features
JavaScript
875
star
2

wasm-service

HTMX, WebAssembly, Rust, ServiceWorkers
Rust
684
star
3

executor

A minimalistic async/await executor for Rust
Rust
216
star
4

view

a macro for constructing views in Rust πŸ—οΈ
Rust
104
star
5

wasm-module

A web component for running web assembly
JavaScript
77
star
6

watson

a minimilistic web assembly parser, compiler, and interpreter for Rust
Rust
77
star
7

hyperpixel

An extremely fast pixel framebuffer for Rust web assembly 🧱
Rust
62
star
8

rust-roguelike

A simple rust roguelike experiment using web assembly
Rust
55
star
9

webcomponent

A web component library for rust
Rust
55
star
10

pinephone-gtk-rs-starter

Rust
54
star
11

ImageStorage.js

A simple library for using PNG images as key value pair data holders. MIT LICENSE
JavaScript
52
star
12

mars

A data science notebook for Rust
JavaScript
41
star
13

cyberdeck

A library for easily creating WebRTC data channel connections in Rust
Rust
41
star
14

kimono

A terminal style toolkit inspired by CSS for elegant TUIs πŸ‘˜
Rust
40
star
15

mux.js

A data multiplexing library for javascript. MIT LICENSE
JavaScript
37
star
16

shibari.js

Beautiful bindings and nothing else
JavaScript
37
star
17

conifer

Rust
37
star
18

js_ffi

Dynamically invoke javascript from web assembly
Rust
36
star
19

voir

A simple router for lit-html
JavaScript
34
star
20

webblock

The simplest way to make expressive and powerful web components
JavaScript
30
star
21

wasm-script

Compile WebAssembly in your HTML
JavaScript
30
star
22

lit-html-rs

lit-html in Rust
Rust
30
star
23

babylon.rs

A WebAssembly wrapper for babylon.js in Rust
Rust
29
star
24

ukiyoe

A Rust library for rendering images to terminals
Rust
28
star
25

aframe-canvas

A library for adding canvas into aframe VR
JavaScript
28
star
26

epistemology

A simple and clear way of hosting llama.cpp as a private HTTP API using Rust
Rust
26
star
27

aframe-webvr-controller

A component for quickly attaching objects to webvr controllers in a-frame
JavaScript
24
star
28

rust-webcomponent

A simple web component implementation using stdweb
JavaScript
24
star
29

leptos_three

A prototype of creating a React Three Fiber like experience with Leptos and ThreeJS
Rust
24
star
30

gestured

A simple gesture daemon in Rust
Rust
23
star
31

aframe-html

A aframe component for rendering and interacting with html in VR
JavaScript
22
star
32

aws-lambda-api-rust

A sample project for showing how to create an aws lambda api with rust and terraform
Rust
21
star
33

avatar-poser

an avatar animation builder for the metaverse
TypeScript
20
star
34

gbnf

A library for working with GBNF files
Rust
19
star
35

no_error

A simple error library for no_std + no_alloc Rust
Rust
18
star
36

pig

A simple PostgreSQL data migration tool
Rust
18
star
37

c-to-webassembly

Using clang and llvm to compile C into Web Assembly
C
17
star
38

slamburger

A SLAM algorithm for WebAssembly πŸ”
Rust
17
star
39

spark_delta_lake

Python
16
star
40

pinephone-cairo-game-starter

Example of a game for PinePhone using Cairo
Rust
16
star
41

webcompose

Create web components with functional composition
JavaScript
16
star
42

rust-simple-virtual-dom

A very simple virtual dom implementation in Rust and Web Assembly
Rust
16
star
43

woke

A minimalist waker for async-await executors
Rust
15
star
44

staticflux

JavaScript
15
star
45

vala-web-assembly

proof of concept of vala and web assembly
C
15
star
46

lets-build-wasm-interpreter

Let's build a web assembly interpreter!
HTML
15
star
47

llvm-wasm

The most minimal wasm llvm project
HTML
15
star
48

mochi

A simple game engine using Gtk & Cairo
Rust
14
star
49

virtual-dom-rs-counter

Implementation of react/redux style UI development in Rust
Rust
14
star
50

http-server

A dead simple http server for serving local files for development purposes
Rust
13
star
51

globals

Painless globals in Rust πŸ”­πŸŒβœ¨
Rust
12
star
52

legacy_wabisabi

A modular web assembly microkernel os for the web
JavaScript
12
star
53

rxjs-pubsub

Simple publish-subscription data structure using rxjs
JavaScript
11
star
54

libw

A human library for easily using wasi
Rust
11
star
55

asynctimer

A minimal toy async-await executor in web assembly
Rust
11
star
56

cryptoidentity

A library for simple crypto identity in the browser
JavaScript
10
star
57

web-local-storage-api

A pure Rust implementation of the Web Local Storage API, for use in non-browser contexts
Rust
10
star
58

SylvesterClosure

An Google Closure ready implementation of sylvester vector and matrix math library.
JavaScript
9
star
59

emoji-rs

Rust
9
star
60

hypershape

A hypermedia system for the metaverse inspired by Web 1.0 πŸ”ΊπŸŸ’ 🟦
TypeScript
8
star
61

aframe-keyboard

JavaScript
7
star
62

posterity_ukiyoe

A renderer agnostic GUI library
Rust
7
star
63

pong

pong in web assembly Rust
Rust
7
star
64

pinephone-electron-starter

Run electron app on pinephone
JavaScript
7
star
65

parallelogram

A library for distributing functional processing across web workers
JavaScript
7
star
66

virtual-dom-rs-hello-world

Rust
7
star
67

webassembly-rs

A Rust library for working with WebAssembly bytecode.
Rust
7
star
68

wasi.run

Run WASI anywhere.
TypeScript
6
star
69

keyvalue.js

A simple server for key value storage on heroku. Look at complete instructions below.
JavaScript
6
star
70

ClosureStackNodeJS

A templated webstack that uses NodeJS,Google Closure, JSDoc, Express, and django/jinja like templates. Basically this is a boilerplate project meant to reduce a lot of common steps to setup for using these technologies. Apache 2 licensed.
JavaScript
6
star
71

aframe-vuejs

HTML
5
star
72

usdz

A parser of USDZ file format in Rust
Rust
5
star
73

crdt-todo

An example application using CRDT library Automerge to make a TODO app
TypeScript
5
star
74

neonorigami

An open-source virtual world platform built on A-Frame
JavaScript
5
star
75

gago

A genetics algorithm library with speciation written in Go
Go
5
star
76

julia-opengl

A simple opengl example
Julia
5
star
77

FalloutMUD

A fan fiction MUD based in the Fallout universe.
JavaScript
5
star
78

cleanstack-isomorphic

CSS
5
star
79

pbr-scene

A simple web component library for using Google Filament
JavaScript
5
star
80

aframe-vive-starter

A simple starter project for aframe with vive
JavaScript
5
star
81

CleanStackGAE

My uber clean python web stack for Google App Engine using CherryPy, Jinja2, and REST.
Python
4
star
82

string_concat

A useful string concatenation macro for no_std Rust
Rust
4
star
83

metamorphosis

A GPGPU computation graph executor for web assembly πŸŒŸπŸ›πŸ¦‹
Rust
4
star
84

Logo

An old school logo implementation in HTML 5
JavaScript
4
star
85

generational-arena

A generational arena allocator for javascript
JavaScript
4
star
86

GenericRogue

JavaScript
4
star
87

FalloutCSS

Fallout 3 Terminal in HTML/CSS 3. Feel free to use for any purpose.
Shell
4
star
88

gundb_webrtc

A demonstration of WebRTC using distributed storage (GunDB) as signalling
JavaScript
4
star
89

shoji

A VBox/HBox layout library for Rust
Rust
3
star
90

TypeScriptChromeApp

A simple starter setup for a chrome app written in typescript.
JavaScript
3
star
91

julia-roguelike

A simple demo of a roguelike starter in Julia
Julia
3
star
92

cstring

A super simple library for c strings oriented toward web assembly needs
Rust
3
star
93

waste

A web assembly optimizer
Rust
3
star
94

stores

a reduceable store for Rust
Rust
3
star
95

save

a simple command for saving input steam
Rust
3
star
96

wcurses

a simple terminal control library for wasi
Rust
3
star
97

godot_openxr__rust

A simple Godot OpenXR Rust project that shows how to use trigger buttons and physical based rendering (PBR) on Vulkan graphics
GDScript
3
star
98

GooglePaymentsNodeJS

JavaScript
2
star
99

Underdark

A multiplayer roguelike game written in nodejs
JavaScript
2
star
100

Palettizer

2
star