0016-wasm-康威生命游戏
作者:互联网
环境
- Time 2022-05-16
- Rust 1.60.0
- Node 12.22.5
- wasm-pack 0.10.2
前言
说明
参考:https://rustwasm.github.io/docs/book/game-of-life/implementing.html
目标
在上一节的基础上进行,前面已经实现了康威游戏,只不过是直接将字符串渲染到页面上的,接下来使用 canvas
渲染。
index.html
将之前的 pre
标签修改为 canvas
标签。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>康威生命游戏</title>
<style>
body {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<canvas id="game"></canvas>
<script src="./bootstrap.js"></script>
</body>
</html>
暴露细胞列表地址
#[wasm_bindgen]
impl Universe {
...
pub fn cells(&self) -> *const Cell {
self.cells.as_ptr()
}
...
}
index.js
之后就是 index.js 之中的内容。
导入
import { Universe, Cell } from "game";
import { memory } from "game/game_bg";
常量定义
const CELL_SIZE = 10;
const GRID_COLOR = "#CCCCCC";
const DEAD_COLOR = "#FFFFFF";
const ALIVE_COLOR = "#000000";
const WIDTH = 64;
const HEIGHT = 64;
获取画布
const canvas = document.getElementById("game");
canvas.height = (CELL_SIZE + 1) * HEIGHT + 1;
canvas.width = (CELL_SIZE + 1) * WIDTH + 1;
const ctx = canvas.getContext('2d');
循环渲染
const universe = Universe.new(WIDTH, HEIGHT);
const renderLoop = () => {
universe.tick();
drawGrid();
drawCells();
requestAnimationFrame(renderLoop);
};
画栅格
const drawGrid = () => {
ctx.beginPath();
ctx.strokeStyle = GRID_COLOR;
for (let i = 0; i <= WIDTH; i++) {
ctx.moveTo(i * (CELL_SIZE + 1) + 1, 0);
ctx.lineTo(i * (CELL_SIZE + 1) + 1, (CELL_SIZE + 1) * HEIGHT + 1);
}
for (let j = 0; j <= HEIGHT; j++) {
ctx.moveTo(0, j * (CELL_SIZE + 1) + 1);
ctx.lineTo((CELL_SIZE + 1) * WIDTH + 1, j * (CELL_SIZE + 1) + 1);
}
ctx.stroke();
};
画细胞
const drawCells = () => {
const cellsPtr = universe.cells();
const cells = new Uint8Array(memory.buffer, cellsPtr, WIDTH * HEIGHT);
ctx.beginPath();
for (let row = 0; row < HEIGHT; row++) {
for (let col = 0; col < WIDTH; col++) {
const idx = row * WIDTH + col;
ctx.fillStyle = cells[idx] === Cell.Dead ? DEAD_COLOR : ALIVE_COLOR;
ctx.fillRect(col * (CELL_SIZE + 1) + 1, row * (CELL_SIZE + 1) + 1, CELL_SIZE, CELL_SIZE);
}
}
ctx.stroke();
};
入口
drawGrid();
drawCells();
requestAnimationFrame(renderLoop);
启动前端
npm run start
效果展示
总结
使用 canvas
来渲染康威生命游戏的效果。
附录
标签:0016,canvas,const,康威,ctx,CELL,WIDTH,wasm,SIZE 来源: https://www.cnblogs.com/jiangbo4444/p/16636647.html