-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
75 lines (58 loc) · 2.19 KB
/
Copy pathindex.js
File metadata and controls
75 lines (58 loc) · 2.19 KB
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
// Imports are from the demo-util folder in the repo
// https://github.com/torch2424/wasm-by-example/blob/master/demo-util/
import { wasmBrowserInstantiate } from "/demo-util/instantiateWasm.js";
const runWasm = async () => {
// Instantiate our wasm module
const wasmModule = await wasmBrowserInstantiate("./index.wasm");
// Get our exports object, with all of our exported Wasm Properties
const exports = wasmModule.instance.exports;
// Get our memory object from the exports
const memory = exports.memory;
// Create a Uint8Array to give us access to Wasm Memory
const wasmByteMemoryArray = new Uint8Array(memory.buffer);
// Get our canvas element from our index.html
const canvasElement = document.querySelector("canvas");
// Set up Context and ImageData on the canvas
const canvasContext = canvasElement.getContext("2d");
const canvasImageData = canvasContext.createImageData(
canvasElement.width,
canvasElement.height
);
// Clear the canvas
canvasContext.clearRect(0, 0, canvasElement.width, canvasElement.height);
const getDarkValue = () => {
return Math.floor(Math.random() * 100);
};
const getLightValue = () => {
return Math.floor(Math.random() * 127) + 127;
};
const drawCheckerBoard = () => {
const checkerBoardSize = 20;
// Generate a new checkboard in wasm
exports.generateCheckerBoard(
getDarkValue(),
getDarkValue(),
getDarkValue(),
getLightValue(),
getLightValue(),
getLightValue()
);
// Pull out the RGBA values from Wasm memory, the we wrote to in wasm,
// starting at the checkerboard pointer (memory array index)
const imageDataArray = wasmByteMemoryArray.slice(
exports.CHECKERBOARD_BUFFER_POINTER.valueOf(),
exports.CHECKERBOARD_BUFFER_SIZE.valueOf()
);
// Set the values to the canvas image data
canvasImageData.data.set(imageDataArray);
// Clear the canvas
canvasContext.clearRect(0, 0, canvasElement.width, canvasElement.height);
// Place the new generated checkerboard onto the canvas
canvasContext.putImageData(canvasImageData, 0, 0);
};
drawCheckerBoard();
setInterval(() => {
drawCheckerBoard();
}, 1000);
};
runWasm();