-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
58 lines (45 loc) · 1.93 KB
/
index.js
File metadata and controls
58 lines (45 loc) · 1.93 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
import wasmInit from "./rustracer_wasm/wasm.js";
const runWasm = async () => {
// Instantiate our wasm module
const rustWasm = await wasmInit("./rustracer_wasm/wasm_bg.wasm");
// See https://rustwasm.github.io/book/reference/debugging.html#logging-panics
rustWasm.init_panic_hook();
// Create a Uint8Array to give us access to Wasm Memory
const wasmByteMemoryArray = new Uint8Array(rustWasm.memory.buffer);
// Get our canvas element from our index.html
const canvasElement = document.querySelector("canvas");
const width = rustWasm.get_width();
const height = rustWasm.get_height();
canvasElement.width = width;
canvasElement.height = height;
// 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 drawScene = () => {
// Generate a new scene in wasm
rustWasm.render();
// Create a Uint8Array to give us access to Wasm Memory
const wasmByteMemoryArray = new Uint8Array(rustWasm.memory.buffer);
// Pull out the RGBA values from Wasm memory
// Starting at the memory index of out output buffer (given by our pointer)
// 200 * 200 * 4 = checkboard max X * checkerboard max Y * number of pixel properties (R,G.B,A)
const outputPointer = rustWasm.get_output_buffer_pointer();
const imageDataArray = wasmByteMemoryArray.slice(
outputPointer,
outputPointer + width * height * 4
);
// 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);
};
drawScene();
};
runWasm();