Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html>

<head>
  <style>
    body {
      background-color: black;
    }

    canvas {
      border: 2px gray solid;
    }
  </style>
</head>

<body style="background-color: black;">
  <div><button>Refresh</button></div>
  <canvas></canvas>
</body>

</html>
              
            
!

CSS

              
                
              
            
!

JS

              
                const N = 8;
const RANDOM_INITIAL_RANGE = 10;
const MATRIX_LENGTH = Math.pow(2, N) + 1;
const CANVAS_HEIGHT = MATRIX_LENGTH * 2;
const CANVAS_WIDTH = MATRIX_LENGTH * 2;
const MATRIX_DIMENSIONS = {
  pixelHeight: CANVAS_HEIGHT / MATRIX_LENGTH,
  pixelWidth: CANVAS_WIDTH / MATRIX_LENGTH
};
const canvas = document.querySelector("canvas");
canvas.height = CANVAS_HEIGHT;
canvas.width = CANVAS_WIDTH;

function getColor(percentage) {
  return landscapeColors(percentage);
}

function landscapeColors(percentage) {
  const hue = percentage >= 0.66 ? 240 : percentage >= 0.33 ? 120 : 0;
  const lightness = 50;
  const saturation = 100;

  return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
}

function draw(terrain_matrix) {
  const ctx = canvas.getContext("2d");
  ctx.clearRect(0, 0, CANVAS_HEIGHT, CANVAS_WIDTH);
  ctx.beginPath();
  terrain_matrix.forEach((pixelsRow, rowIndex) => {
    const y = rowIndex * MATRIX_DIMENSIONS.pixelHeight;
    pixelsRow.forEach((pixel, pixelIndex) => {
      const x = pixelIndex * MATRIX_DIMENSIONS.pixelWidth;
      ctx.fillStyle = getColor(pixel);
      ctx.fillRect(
        x,
        y,
        MATRIX_DIMENSIONS.pixelWidth,
        MATRIX_DIMENSIONS.pixelHeight
      );
    });
  });
  ctx.closePath();
}

function randomInRange(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

function generateMatrix() {
  const matrix = new Array(MATRIX_LENGTH)
    .fill(0)
    .map(() => new Array(MATRIX_LENGTH).fill(null));

  matrix[0][MATRIX_LENGTH - 1] = randomInRange(0, RANDOM_INITIAL_RANGE);
  matrix[MATRIX_LENGTH - 1][0] = randomInRange(0, RANDOM_INITIAL_RANGE);
  matrix[0][0] = randomInRange(0, RANDOM_INITIAL_RANGE);
  matrix[MATRIX_LENGTH - 1][MATRIX_LENGTH - 1] = randomInRange(
    0,
    RANDOM_INITIAL_RANGE
  );

  return matrix;
}

function calculateSquare(matrix, chunkSize, randomFactor) {
  let sumComponents = 0;
  let sum = 0;
  for (let i = 0; i < matrix.length - 1; i += chunkSize) {
    for (let j = 0; j < matrix.length - 1; j += chunkSize) {
      const BOTTOM_RIGHT = matrix[j + chunkSize]
        ? matrix[j + chunkSize][i + chunkSize]
        : null;
      const BOTTOM_LEFT = matrix[j + chunkSize]
        ? matrix[j + chunkSize][i]
        : null;
      const TOP_LEFT = matrix[j][i];
      const TOP_RIGHT = matrix[j][i + chunkSize];
      const { count, sum } = [
        BOTTOM_RIGHT,
        BOTTOM_LEFT,
        TOP_LEFT,
        TOP_RIGHT
      ].reduce(
        (result, value) => {
          if (isFinite(value) && value != null) {
            result.sum += value;
            result.count += 1;
          }
          return result;
        },
        { sum: 0, count: 0 }
      );
      matrix[j + chunkSize / 2][i + chunkSize / 2] =
        sum / count + randomInRange(-randomFactor, randomFactor);
    }
  }
}

function calculateDiamond(matrix, chunkSize, randomFactor) {
  const half = chunkSize / 2;
  for (let y = 0; y < matrix.length; y += half) {
    for (let x = (y + half) % chunkSize; x < matrix.length; x += chunkSize) {
      const BOTTOM = matrix[y + half] ? matrix[y + half][x] : null;
      const LEFT = matrix[y][x - half];
      const TOP = matrix[y - half] ? matrix[y - half][x] : null;
      const RIGHT = matrix[y][x + half];
      const { count, sum } = [BOTTOM, LEFT, TOP, RIGHT].reduce(
        (result, value) => {
          if (isFinite(value) && value != null) {
            result.sum += value;
            result.count += 1;
          }
          return result;
        },
        { sum: 0, count: 0 }
      );
      matrix[y][x] = sum / count + randomInRange(-randomFactor, randomFactor);
    }
  }
  return matrix;
}

function diamondSquare(matrix) {
  let chunkSize = MATRIX_LENGTH - 1;
  let randomFactor = RANDOM_INITIAL_RANGE;

  while (chunkSize > 1) {
    calculateSquare(matrix, chunkSize, randomFactor);
    calculateDiamond(matrix, chunkSize, randomFactor);
    chunkSize /= 2;
    randomFactor /= 2;
  }

  return matrix;
}

function normalizeMatrix(matrix) {
  const maxValue = matrix.reduce((max, row) => {
    return row.reduce((max, value) => Math.max(value, max));
  }, -Infinity);

  return matrix.map((row) => {
    return row.map((val) => val / maxValue);
  });
}

function copyMatrix(matrix) {
  return JSON.parse(JSON.stringify(matrix));
}

function start() {
  console.log("Start");
  const matrix = diamondSquare(generateMatrix());
  const normalizedMatrix = normalizeMatrix(matrix);
  console.log("Finish");
  draw(normalizedMatrix);
}

start();

document.querySelector("button").addEventListener("click", start);

              
            
!
999px

Console