JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="grayscaleCanvas" class="greyscaleCanvas" width="257px" height="257px"></canvas>
CSS
.greyscaleCanvas {
border: solid 1px black;
}
JavaScript
function HeightMap(sideLength, maxHeight, roughness) {
const n = Math.log(sideLength - 1) / Math.log(2);
if (n < 0 || n % 1 != 0) {
throw "Invalid side length in Diamond Square: Side Length has to be in range of `(2^n) + 1`.";
}
let gridArray = new Array(sideLength);
for (var i = 0; i < gridArray.length; i++) {
gridArray[i] = new Float32Array(sideLength);
}
gridArray = _initGrid(gridArray, sideLength, maxHeight);
gridArray = _seed(gridArray, sideLength, roughness);
return gridArray;
}
function _initGrid(gridArray, sideLength, maxHeight) {
gridArray[0][0] = RandomInt(0, maxHeight); // NW
gridArray[0][sideLength-1] = RandomInt(0, maxHeight); // NE
gridArray[sideLength-1][sideLength-1] = RandomInt(0, maxHeight); // SE
gridArray[sideLength-1][0] = RandomInt(0, maxHeight); // SW
return gridArray;
}
function _seed(gridArray, sideLength, roughness) {
let step = sideLength - 1;
let size = sideLength - 1;
let currentRoughness = roughness;
let run_num = 0
while (step / 2 >= 1) {
console.log(run_num)
run_num = run_num + 1
let numSquares = Math.pow(size, 2) / Math.pow(step, 2);
let perRowSquares = Math.floor(Math.sqrt(numSquares));
for (let i = 0; i < perRowSquares; i++) {
for (let j = 0; j < perRowSquares; j++) {
row = i*step
col = j*step
const squareCornerValues = _getSquareCornerValues(gridArray, row, col, step)
gridArray = _diamondStep(squareCornerValues, row, col, step, gridArray, currentRoughness);
gridArray = _squareStep(row, col, step, gridArray, sideLength, currentRoughness)
// _squareStep(diamondMidPoints, gridArray, step, currentRoughness);
}
}
currentRoughness /= 2.0;
step /= 2;
}
return gridArray;
}
function _diamondStep(squareCornerValues, i, j, step, gridArray, currentRoughness) {
gridArray[row+step/2][col+step/2] = (squareCornerValues[0] + squareCornerValues[1] + squareCornerValues[2] + squareCornerValues[3] ) /...