boardToPic

This commit is contained in:
Ali Gator 2022-12-19 22:53:48 +01:00
parent a402739b97
commit e43bd48794
2 changed files with 22 additions and 16 deletions

View File

@ -28,13 +28,14 @@
servietteRules,
evolve2d,
} from "../modules/automata.js";
import { getRandomInt, sleep } from "../modules/common.js";
import { picToBoard, picToBlackAndWhite } from "../modules/picture.js";
import { getRandomInt } from "../modules/common.js";
import { boardToPic, picToBoard } from "../modules/picture.js";
export default {
name: "CanvasBoard",
data() {
return {
board: null,
canvas: null,
workCanvas: null,
workCtx: null,
@ -65,13 +66,13 @@
boardWidth: "boardWidth",
boardHeight: "boardHeight",
selected2dRules: "selected2dRules",
picture: "picture",
}),
...mapWritableState(globalStore, {
lastBoard: "lastBoard",
canvasWidth: "canvasWidth",
canvasHeight: "canvasHeight",
getReset: "reset",
picture: "picture",
}),
// used to determine the dimensions of the board
max() {
@ -120,21 +121,13 @@
drawCanvas(board, width, height) {
const d = this.cellProperties.size;
// bool to RGBA colors
const img = board.flat().reduce((acc, cell, index) => {
const color = cell === 1 ? 0 : 255;
const i = index * 4;
acc.data[i] = color;
acc.data[i + 1] = color;
acc.data[i + 2] = color;
acc.data[i + 3] = 255;
return acc;
}, new ImageData(width, height));
const img = boardToPic(board, width, height);
// rescale and draw
this.ctx.save();
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
this.workCtx.putImageData(img, 0, 0);
this.ctx.imageSmoothingEnabled = false;
if (this.getDraw2dPicture != true) this.ctx.scale(d, d);
this.ctx.scale(d, d);
this.ctx.drawImage(
this.workCanvas,
0,
@ -181,7 +174,6 @@
const newBoard = evolve2d(board, this.selectedRules);
this.draw2d(board);
this.lastBoard = Object.freeze(newBoard);
/* await sleep(this.refreshRate) */
return this.draw2dNext(newBoard);
});
},
@ -189,7 +181,7 @@
async draw2dNew() {
if (!this.canDraw) return;
const initialState = this.randomInitialState();
let board = evolve2d(initialState, conwayRules);
let board = evolve2d(initialState, this.selectRules);
if (this.loop) return this.draw2dNext(board);
else this.draw2d(board);
this.toggleStop();

View File

@ -35,5 +35,19 @@ export function picToBoard(pixels, width, height) {
}
return acc;
}, []);
return toMatrix(flat, Math.max(width, height));
return toMatrix(flat, width, height);
}
// convert board to ImageData
export function boardToPic(board, width, height) {
return board.flat().reduce((acc, cell, index) => {
const color = cell === 1 ? 0 : 255;
const i = index * 4;
acc.data[i] = color;
acc.data[i + 1] = color;
acc.data[i + 2] = color;
acc.data[i + 3] = 255;
return acc;
}, new ImageData(width, height));
}