单文件WebAssembly html演示

时间:2018-09-30 21:30:15

标签: javascript html webassembly

在哪里可以找到最简单的一文件演示,以演示html中WebAssembly的用法?

JavaScript示例很简单:

<script>
function hw() { console.log("Hello, world."); }
</script>
<button onclick="hw()">HW</button>

是否有WebAssembly类似物?

我希望它具有类似硬件的硬编码字节缓冲区和wasm二进制文件,该缓冲区将被加载并执行一些琐碎的功能。这是我期望的概述:

<script>
function hw() { 
    var wasm_code = [255, 0, 128, ..., whatever, ...];
    var magic = give_me_wasm(wasm_code);
    var x = magic.my_add(2,2);
    console.log("2 + 2 = ", x); 
}
</script>
<button onclick="hw()">HW</button>

这样的演示能否完成,它可以粘贴到开发者控制台中并且可以在不设置任何框架和工具的情况下进行尝试?

2 个答案:

答案 0 :(得分:1)

自己做:

<script>
var wasm_base64;
var wasm_buffer;
var wasm;
var wasm_instance;
function hw() {
    wasm_base64 = "AGFzbQEAAAABBwFgAnx8AXwDAgEABwoBBm15X2FkZAAACgkBBwAgACABoAs=";
    wasm_buffer = Uint8Array.from(atob(wasm_base64), c => c.charCodeAt(0)).buffer;
    WebAssembly.compile(wasm_buffer).then(x => {
        wasm = x;
        wasm_instance = new WebAssembly.Instance(wasm);
        var x = wasm_instance.exports.my_add(2,2);
        console.log("2+2 = ",x);
    });
}
</script>
<button onclick="hw()">HW</button>

这是嵌入式WebAssembly文本格式(q.wat):

(module
  (type (;0;) (func (param f64 f64) (result f64)))
  (func $myadd (type 0) (param f64 f64) (result f64)
    get_local 0
    get_local 1
    f64.add)
  (export "my_add" (func $myadd))
)

以下是生成base64缓冲区的命令行:

$ wat2wasm q.wat -o w.wasm
$ base64 -w0 w.wasm ;echo
AGFzbQEAAAABBwFgAnx8AXwDAgEABwoBBm15X2FkZAAACgkBBwAgACABoAs=
可以使用开发者控制台浏览

wasmwasm_instance对象。

在Firefox 63.0b9中进行了检查。

答案 1 :(得分:1)

This是我在Gist上发现的一个经过充分评论的示例。将代码嵌入您的<script>标记中,您将获得一个“单文件WebAssembly html演示”

为方便起见,在此处复制

// this code is from a simple add function in c:
//
// // hello.c
// int add(int a, int b) {
//    return a + b;
// }

//
// compiles it with emcc (http://webassembly.org/getting-started/developers-guide/)
// $ git clone https://github.com/juj/emsdk.git
// $ cd emsdk
// $ ./emsdk install latest
// $ ./emsdk activate latest
// $ source ./emsdk_env.sh --build=Release
//
// once installed:
//
// $ emcc hello.c -s ONLY_MY_CODE=1 -s WASM=1 -s EXPORTED_FUNCTIONS="['_add']" -o hello.js
//
// yes, not sure why we have to add '_' in front of the exported function.
// take the hello.wasm and serialize it to base64, e.g. using node

// const code = fs.readFileSync('./hello.wasm')
// code.toString('base64')
// AGFzbQEAAAABCwJgAX8AYAJ/fwF/An4HA2VudgZtZW1vcnkCAYACgAIDZW52BXRhYmxlAXABAAADZW52Cm1lbW9yeUJhc2UDfwADZW52CXRhYmxlQmFzZQN/AANlbnYIU1RBQ0tUT1ADfwADZW52CVNUQUNLX01BWAN/AANlbnYSYWJvcnRTdGFja092ZXJmbG93AAADAgEBBhMDfwEjAgt/ASMDC30BQwAAAAALBwgBBF9hZGQAAQkBAAo7ATkBB38jBCEIIwRBEGokBCMEIwVOBEBBEBAACyAAIQIgASEDIAIhBCADIQUgBCAFaiEGIAgkBCAGDws=


// https://www.npmjs.com/package/base64-arraybuffer
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

// Use a lookup table to find the index.
const lookup = new Uint8Array(256);
for (let i = 0; i < chars.length; i++) {
    lookup[chars.charCodeAt(i)] = i;
}

function decode(base64) {
  var bufferLength = base64.length * 0.75,
      len = base64.length, i, p = 0,
      encoded1, encoded2, encoded3, encoded4;

  if (base64[base64.length - 1] === "=") {
    bufferLength--;
    if (base64[base64.length - 2] === "=") {
      bufferLength--;
    }
  }

  var arraybuffer = new ArrayBuffer(bufferLength),
      bytes = new Uint8Array(arraybuffer);

  for (i = 0; i < len; i+=4) {
    encoded1 = lookup[base64.charCodeAt(i)];
    encoded2 = lookup[base64.charCodeAt(i+1)];
    encoded3 = lookup[base64.charCodeAt(i+2)];
    encoded4 = lookup[base64.charCodeAt(i+3)];

    bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
    bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
    bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  }

  return arraybuffer;
} 

// this is the serialized code.
const code = 'AGFzbQEAAAABCwJgAX8AYAJ/fwF/An4HA2VudgZtZW1vcnkCAYACgAIDZW52BXRhYmxlAXABAAADZW52Cm1lbW9yeUJhc2UDfwADZW52CXRhYmxlQmFzZQN/AANlbnYIU1RBQ0tUT1ADfwADZW52CVNUQUNLX01BWAN/AANlbnYSYWJvcnRTdGFja092ZXJmbG93AAADAgEBBhMDfwEjAgt/ASMDC30BQwAAAAALBwgBBF9hZGQAAQkBAAo7ATkBB38jBCEIIwRBEGokBCMEIwVOBEBBEBAACyAAIQIgASEDIAIhBCADIQUgBCAFaiEGIAgkBCAGDws='
const buffer = decode(code)

// bootstrap the env.
const memory = new WebAssembly.Memory({ initial: 256, maximum: 256 })
const importObj = {
    env: {
        abortStackOverflow: () => { throw new Error('overflow'); },
        table: new WebAssembly.Table({ initial: 0, maximum: 0, element: 'anyfunc' }),
        tableBase: 0,
        memory: memory,
        memoryBase: 1024,
        STACKTOP: 0,
        STACK_MAX: memory.buffer.byteLength,
    }
}

// instantiate
WebAssembly.instantiate(buffer, importObj)
  // take a look at that _add.
  .then(({module, instance}) => { console.log(instance.exports._add(1, 2)) })
  .catch((err) => { console.log(err.message) })