Where can I find a simplest one-file demo showing usage of WebAssembly in html?
JavaScript example is easy:
<script>
function hw() { console.log("Hello, world."); }
</script>
<button onclick="hw()">HW</button>
Is there a WebAssembly analogue?
I expect it to have something like a hard-coded byte buffer with a wasm binary, which is loaded and some trivial function of it is executed. Here is outline of what I expect:
<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>
Can such demo be done, it a simple form that can be pasted in Developer Console and tried without setting up any frameworks and tools?
Done myself:
<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>
Here is embedded WebAssembly text form (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))
)
Here are command lines to generate that base64 buffer:
$ wat2wasm q.wat -o w.wasm
$ base64 -w0 w.wasm ;echo
AGFzbQEAAAABBwFgAnx8AXwDAgEABwoBBm15X2FkZAAACgkBBwAgACABoAs=
wasm
and wasm_instance
objects can be explored using Developer Console.
Checked in Firefox 63.0b9.