Skip to content

Instantly share code, notes, and snippets.

@vyuvalv
Last active November 22, 2020 12:27
Show Gist options
  • Save vyuvalv/fd5508ecf518ed6bf8400d0622777e13 to your computer and use it in GitHub Desktop.
Save vyuvalv/fd5508ecf518ed6bf8400d0622777e13 to your computer and use it in GitHub Desktop.
Renders the grid on canvas
// Sets the height and width
// Clear context
// Drawing the grid on canvas
renderGrid(grid) {
this.context = this.getCanvasContext();
// Sets width and Height
this.columnWidth = this.context.width / this.columns;
this.rowHeight = this.context.height / this.rows;
let universe = grid;
for (let i = 0; i < this.columns; i++) {
for (let j = 0; j < this.rows; j++) {
this.renderCell(universe[i][j], i * this.columnWidth, j * this.rowHeight, this.columnWidth, this.rowHeight );
}
}
return universe;
}
// Init Canvas
getCanvasContext() {
const canvas = this.template.querySelector('canvas');
// setting the canvas to container size
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
const ctx = canvas.getContext("2d");
ctx.width = canvas.clientWidth;
ctx.height = canvas.clientHeight;
// Clear canvas
ctx.clearRect(0, 0, ctx.width, ctx.height);
return ctx;
}
// Drawing
renderCell(state, x, y, width, height) {
this.context.beginPath();
this.context.fillStyle = state === 1 ? this.aliveColor : this.deadColor;
this.context.clearRect(x,y, width, height);
this.context.rect(x, y, width, height);
this.context.stroke();
this.context.fill();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment