import wasmInit from "./pkg/gamarjoba.js" const runWasm = async () => { const rustWasm = await wasmInit("./pkg/gamarjoba_bg.wasm"); const result = rustWasm.de_iavascriptis(0, 1); console.log("Should be undefined: ", rustWasm.add_integer_with_constant); const div = document.querySelector("#textBuf"); div.textContent = `Gamarjoba! result: ${result}`; const NUMBER = 257; console.log("Write in WASM, read in JS"); rustWasm.store_value_in_wasm_mem_idx_0(NUMBER); let wasmMemory = new Uint8Array(rustWasm.memory.buffer); let ptr = rustWasm.get_wasm_mem_buffer_pointer(); console.log("Pointer from rust: ", ptr); console.log(wasmMemory[ptr+0]); // should be NUMBER, wrapped around 256 console.log("Write in JS, read in wasm"); wasmMemory[ptr+1] = 15; console.log(rustWasm.read_wasm_mem_buffer_idx_1()); // should be 15 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 ); canvasContext.clearRect(0, 0, canvasElement.width, canvasElement.height); const getDarkValue = () => Math.floor(Math.random() * 100); const getLightValue = () => Math.floor(Math.random() * 127) + 127; const drawCheckerBoard = () => { const checkerBoardSize = 20; // Generate a new checkboard in wasm rustWasm.generate_checkerboard( getDarkValue(), getDarkValue(), getDarkValue(), getLightValue(), getLightValue(), getLightValue() ); // Pull out the RGBA values from Wasm memory // Starting at the memory index of out output buffer (given by our pointer) // 20 * 20 * 4 = checkboard max X * checkerboard max Y * number of pixel properties (R,G.B,A) const outputPointer = rustWasm.get_output_buf_ptr(); const imageDataArray = wasmMemory.slice( outputPointer, outputPointer + checkerBoardSize * checkerBoardSize * 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); }; drawCheckerBoard(); setInterval(() => { drawCheckerBoard(); }, 300); }; runWasm();