标签:0016 canvas const 康威 ctx CELL WIDTH wasm SIZE
环境
- 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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。