-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
96 lines (82 loc) · 3.17 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<!DOCTYPE html>
<html>
<head>
<title>Postfix-Haskell WASM Demo</title>
<style>
html, body {
height: 100%;
margin: 0;
}
body {
background: black;
display: flex;
align-items: center;
justify-content: center;
}
canvas {
border: 1px solid white;
}
</style>
</head>
<body onclick="mod.instance.exports.loop()">
<canvas width="400" height="500" id="game"></canvas>
<script>
(async () => {
// Get canvas 2d context
const canvas = document.getElementById('game');
const context = canvas.getContext('2d');
// Instantiate wasm
const resp = await fetch('game.wasm');
const wasm = await resp.arrayBuffer();
const mod = await WebAssembly.instantiate(wasm, {
js: {
'console.log': console.log,
setFill(r, g, b) {
context.fillStyle = `rgb(${r}, ${g}, ${b})`;
},
contextFillRect: context.fillRect.bind(context),
contextClearRect: context.clearRect.bind(context),
nextFrame() {
requestAnimationFrame(mod.instance.exports.loop);
},
},
});
// Debugging
window.mod = mod;
window.context = context;
window.showMem = () => {
const arr = [...new Uint32Array(mod.instance.exports.memory.buffer)].slice(0,15)
console.log('ball', arr.slice(0, 4));
console.log('paddle', arr.slice(4, 6));
};
// Get exports
const { loop, arrow_left_down, arrow_right_down, arrow_up, space_down, init }
= mod.instance.exports;
init();
// Listen to keyboard events to move the paddle
document.addEventListener('keydown', function(e) {
if (e.which === 37) {
arrow_left_down();
// console.log('left');
} else if (e.which === 39) {
arrow_right_down();
// console.log('right');
} else if (e.which === 32) {
space_down();
// console.log('space');
}
});
// Listen to keyboard events to stop the paddle if key is released
document.addEventListener('keyup', function(e) {
if (e.which === 37 || e.which === 39) {
arrow_up();
// console.log('keyup', e.which);
}
});
// Start game loop
// loop();
mod.instance.exports.draw();
})();
</script>
</body>
</html>