Skip to content

Instantly share code, notes, and snippets.

@benji6
Created June 16, 2017 13:04
Show Gist options
  • Save benji6/b94cae2f852c559bc8861c8e0623e531 to your computer and use it in GitHub Desktop.
Save benji6/b94cae2f852c559bc8861c8e0623e531 to your computer and use it in GitHub Desktop.
wasm experiments
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WASM</title>
<style>
html {
height: 100%;
}
body {
height: 100%;
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<canvas></canvas>
<script>
const canvas = document.querySelector('canvas')
canvas.width = innerWidth
canvas.height = innerHeight
ctx = canvas.getContext('2d')
ctx.fillStyle = 'black'
ctx.fillRect(0, 0, canvas.width, canvas.height)
const n = Math.round(innerHeight / 2)
const importObj = {}
const render = i32 => {
ctx.fillStyle = 'rgba(0, 0, 0, 0.05)'
ctx.fillRect(0, 0, canvas.width, canvas.height)
const xs = i32.slice(0, n * 2)
ctx.fillStyle = 'red'
for (let i = 0; i < xs.length; i+=2) {
ctx.fillRect(xs[i], xs[i + 1], 1, 1)
}
}
fetch('test.wasm')
.then(response => response.arrayBuffer())
.then(bytes => WebAssembly.instantiate(bytes, importObj))
.then(({instance}) => {
const i32 = new Uint32Array(instance.exports.mem.buffer);
for (let i = 0; i < n * 2; i+=2) {
i32[i] = i
i32[i + 1] = i
}
const renderLoop = () => {
requestAnimationFrame(renderLoop)
instance.exports.main(n * 2)
render(i32)
}
requestAnimationFrame(renderLoop)
});
</script>
</body>
</html>
(module
(memory (export "mem") 1)
(func (export "main") (param $len i32)
(local $end i32)
(local $i i32)
(local $j i32)
i32.const 0 set_local $i
i32.const 0 set_local $j
get_local $len i32.const 4 i32.mul set_local $end
(block $break (loop $top
get_local $i get_local $end i32.eq br_if $break
get_local $i i32.const 4 i32.add set_local $j
get_local $i get_local $i i32.load i32.const 1 i32.add i32.store
get_local $j get_local $j i32.load i32.const 1 i32.sub i32.store
get_local $i i32.const 8 i32.add set_local $i
br $top
))
)
)
(module
(memory (export "mem") 1)
(func (export "main") (param $len i32) (result i32)
(local $end i32)
(local $sum i32)
(local $i i32) i32.const 0 set_local $i
get_local $len i32.const 4 i32.mul set_local $end
(block $break (loop $top
get_local $i get_local $end i32.eq br_if $break
get_local $i i32.load get_local $sum i32.add set_local $sum
get_local $i i32.const 4 i32.add set_local $i
br $top
))
get_local $sum
)
)
(module
(export "main" (func $main))
(func $main (param $n i32) (result i32)
(local $sum i32)
i32.const 0 set_local $sum
(loop $loop
get_local $n get_local $sum i32.add set_local $sum
get_local $n i32.const 1 i32.sub set_local $n
i32.const 1 get_local $n i32.lt_s br_if $loop)
get_local $sum
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment