Create a file named index.html in the /compile-with-llvm directory and populate it with the following contents:
<!doctype html>
<html lang="en-us">
<head>
<title>LLVM Test</title>
</head>
<body>
<h1>LLVM Test</h1>
<canvas id="myCanvas" width="255" height="255"></canvas>
<div style="margin-top: 16px;">
<button id="actionButton" style="width: 100px; height: 24px;">
Pause
</button>
</div>
<script type="application/javascript">
const canvas = document.querySelector('#myCanvas');
const ctx = canvas.getContext('2d');
const importObj = {
env: {
memoryBase: 0,
tableBase: 0,
memory: new WebAssembly.Memory({ initial: 256 }),
table: new WebAssembly.Table({ initial: 8, element: 'anyfunc' }),
abort: console.log,
jsFillRect: function(x, y, w, h) {
ctx.fillStyle = '#0000ff';
ctx.fillRect(x, y, w, h);
},
jsClearRect: function() {
ctx.fillStyle = '#ff0000';
ctx.fillRect(0, 0, 255, 255);
}
}
};
WebAssembly.instantiateStreaming(fetch('main.wasm'), importObj)
.then(({ instance }) => {
const m = instance.exports;
m.init();
const loopRectMotion = () => {
setTimeout(() => {
m.moveRect();
if (m.getIsRunning()) loopRectMotion();
}, 20)
};
document.querySelector('#actionButton')
.addEventListener('click', event => {
const newIsRunning = !m.getIsRunning();
m.setIsRunning(newIsRunning);
event.target.innerHTML = newIsRunning ? 'Pause' : 'Start';
if (newIsRunning) loopRectMotion();
});
loopRectMotion();
});
</script>
</body>
</html>
The contents of this file are very similar to the without-glue.html file from Chapter 5, Creating and Loading a WebAssembly Module. Instead of using the loadWasm() function from the /common/load-wasm.js file, we're using the WebAssembly.instantiateStreaming() function. This allows us to omit an additional <script> element and serve the files directly from the /compile-with-llvm directory.
The _ is omitted from the jsFillRect and jsClearRect functions passed into the importObj. We can omit the _ for the functions present on the instance.exports object as well. LLVM doesn't prefix any of the data/functions passed in or out of the module with a _. In the next section, we'll compile main.cpp and interact with the resultant Wasm file in the browser.