元素,并实例化新Universe的元素:constpre=document.getElementById('game-of-life-canvas');constuniverse=Universe.new();JavaScript运行在[一个requestAnimationFrame循环][requestanimationframe]。在每次迭代中,它将当前的Universe绘制到
,然后运行Universe::tick。constrenderLoop=()=>{pre.textContent=universe.render();universe.tick();requestAnimationFrame(renderLoop);};要开始渲染过程,我们所要做的就是为渲染循环的第一次迭代进行初始调用:
在Rust中生成(和分配)一个String,然后有wasm-bindgen将其转换为有效的JavaScript字符串,来会生成Universe单元格的不必要副本。其实在JavaScript代码知道Universe的宽度和高度,并且可以直接从JavaScript中读取WebAssembly线性内存中的单元格字节,我们就可以修改render方法,用来返回单元数组的开头指针。
首先,让我们把pre,换成了一个
##![allow(unused_variables)]#fnmain(){///Publicmethods,exportedtoJavaScript.#[wasm_bindgen]implUniverse{//...pubfnwidth(&self)->u32{self.width}pubfnheight(&self)->u32{self.height}pubfncells(&self)->*constCell{self.cells.as_ptr()}}#}接下来,在wasm-game-of-life/www/index.js,我们也从wasm-game-of-life导入Cell,和让我们定义JavaScript在渲染Canvas时将使用的一些常量:
import{Universe,Cell}from'wasm-game-of-life';constCELL_SIZE=5;//pxconstGRID_COLOR='#CCCCCC';constDEAD_COLOR='#FFFFFF';constALIVE_COLOR='#000000';现在,让我们重写当前的JS代码(导入除外),不再写入
的textContent,而是专注在