Created
September 24, 2017 09:08
-
-
Save SamuelDavis/c1f8dc4f0596f62a2479468875ad2801 to your computer and use it in GitHub Desktop.
Perfect Square game canvas renderer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" | |
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Document</title> | |
<style> | |
body { | |
background-color: red; | |
} | |
canvas { | |
background-color: green; | |
} | |
.content { | |
text-align: center; | |
} | |
.inner { | |
display: inline-block; | |
} | |
.square { | |
width: 50vmax; | |
height: 50vmax; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="content"> | |
<canvas id="screen" class="inner square"></canvas> | |
</div> | |
<script> | |
class Game { | |
constructor(width = 10, height = 10) { | |
this.map = new Array(height).fill(undefined); | |
this.map.forEach((_, i, arr) => arr[i] = new Array(width).fill(undefined)); | |
this.map.forEach((row, y) => row.forEach((cell, x) => this.map[y][x] = [x, y].join(','))); | |
} | |
} | |
class Screen { | |
constructor(elem, game, width = null, height = null) { | |
this.elem = elem; | |
this.game = game; | |
this.width = width || this.game.map[0].length; | |
this.height = height || this.game.map.length; | |
this.ctx = this.elem.getContext('2d'); | |
this.render(); | |
} | |
render() { | |
const styles = window.getComputedStyle(this.elem); | |
const canvasWidth = parseInt(styles.width.replace('px', '')); | |
const canvasHeight = parseInt(styles.height.replace('px', '')); | |
this.elem.width = canvasWidth; | |
this.elem.height = canvasHeight; | |
const cellWidth = canvasWidth / this.width; | |
const cellHeight = canvasHeight / this.height; | |
this.ctx.textAlign = 'center'; | |
this.ctx.textBaseline = 'middle'; | |
// clear | |
this.ctx.clearRect(0, 0, canvasWidth, canvasHeight); | |
// background | |
this.ctx.fillStyle = '#000000'; | |
this.ctx.fillRect(0, 0, canvasWidth, canvasHeight); | |
// foreground | |
this.ctx.fillStyle = '#ffffff'; | |
this.game.map.forEach((row, y) => row.forEach((cell, x) => { | |
this.ctx.font = `normal normal ${cellWidth / cell.length}px Monospace`; | |
this.ctx.fillText(cell, x * cellWidth + cellWidth / 2, y * cellHeight + cellHeight / 2); | |
})); | |
window.requestAnimationFrame(this.render.bind(this)); | |
} | |
} | |
const game = new Game(); | |
const screen = new Screen(document.getElementById('screen'), game); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment