-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathscript.js
62 lines (51 loc) · 1.86 KB
/
script.js
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
var memory = new WebAssembly.Memory({
// See build.zig for reasoning
initial: 2 /* pages */,
maximum: 2 /* pages */,
});
var importObject = {
env: {
consoleLog: (arg) => console.log(arg), // Useful for debugging on zig's side
memory: memory,
},
};
WebAssembly.instantiateStreaming(fetch("zig-out/bin/checkerboard.wasm"), importObject).then((result) => {
const wasmMemoryArray = new Uint8Array(memory.buffer);
// Automatically set canvas size as defined in `checkerboard.zig`
const checkerboardSize = result.instance.exports.getCheckerboardSize();
const canvas = document.getElementById("checkerboard");
canvas.width = checkerboardSize;
canvas.height = checkerboardSize;
const context = canvas.getContext("2d");
const imageData = context.createImageData(canvas.width, canvas.height);
context.clearRect(0, 0, canvas.width, canvas.height);
const getDarkValue = () => {
return Math.floor(Math.random() * 100);
};
const getLightValue = () => {
return Math.floor(Math.random() * 127) + 127;
};
const drawCheckerboard = () => {
result.instance.exports.colorCheckerboard(
getDarkValue(),
getDarkValue(),
getDarkValue(),
getLightValue(),
getLightValue(),
getLightValue()
);
const bufferOffset = result.instance.exports.getCheckerboardBufferPointer();
const imageDataArray = wasmMemoryArray.slice(
bufferOffset,
bufferOffset + checkerboardSize * checkerboardSize * 4
);
imageData.data.set(imageDataArray);
context.clearRect(0, 0, canvas.width, canvas.height);
context.putImageData(imageData, 0, 0);
};
drawCheckerboard();
console.log(memory.buffer);
setInterval(() => {
drawCheckerboard();
}, 250);
});