Created
July 26, 2021 23:00
-
-
Save 0xdeployer/baf8a1ae5c83d6c6214b8ae6ee1eda4b to your computer and use it in GitHub Desktop.
Function used to render Pixelglyphs using HTML Canvas
This file contains 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
/** | |
The following function is used to re-create Pixelglyphs from on-chain data. | |
Original glyphs were created with the following: | |
const matrix = [ [ 0, 0, 0, 0, 0 ], [ 0, 1, 1, 0, 1 ], [ 0, 1, 1, 0, 0 ], [ 0, 0, 0, 1, 1 ], [ 0, 0, 0, 1, 1 ], [ 0, 1, 1, 1, 1 ], [ 0, 1, 0, 0, 0 ], [ 0, 1, 1, 1, 1 ], [ 0, 1, 1, 1, 1 ], [ 0, 0, 0, 0, 0 ] ]; | |
const colors = [ "rgb(93,19,36)", "rgb(123,234,113)", "rgb(173,109,23)" ]; | |
render(canvasElement, matrix, 37, ...colors); | |
*/ | |
function render( | |
canvas: HTMLCanvasElement, | |
matrix: number[][], | |
ppd: number, | |
fillColor: string, | |
borderColor: string, | |
backgroundColor: string | |
) { | |
const size = matrix.length; | |
let canvasSize = Math.ceil(size * Math.SQRT2); | |
canvasSize += canvasSize % 2; | |
const margin = (canvasSize - size) / 2; | |
canvas.width = canvasSize * ppd; | |
canvas.height = canvasSize * ppd; | |
const ctx = canvas.getContext("2d"); | |
if (!ctx) throw new Error(); | |
ctx.fillStyle = backgroundColor; | |
ctx.fillRect(0, 0, canvas.width, canvas.height); | |
ctx.translate(margin * ppd, margin * ppd); | |
for (let y = 0; y < matrix.length; y++) { | |
const row = matrix[y]; | |
for (let x = 0; x < row.length; x++) { | |
if (row[x] == 1) { | |
ctx.fillStyle = fillColor; | |
} else if (countNeighbors(matrix, x, y) > 0) { | |
ctx.fillStyle = borderColor; | |
} else { | |
continue; | |
} | |
ctx.fillRect(x * ppd, y * ppd, ppd, ppd); | |
ctx.fillRect((size - x - 1) * ppd, y * ppd, ppd, ppd); | |
} | |
} | |
return canvas; | |
} | |
function countNeighbors(pxgGrid: number[][], x: number, y: number) { | |
return ( | |
(pxgGrid[y - 1]?.[x] || 0) + | |
(pxgGrid[y + 1]?.[x] || 0) + | |
(pxgGrid[y][x - 1] || 0) + | |
(pxgGrid[y][x + 1] || 0) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment