npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

js-wasm

v0.5.6

Published

Call JavaScript from WebAssembly

Downloads

26

Readme

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:

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

  • Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
  • MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)

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.