JavaScript Terrain Generator




A class-based tool that allows users to generate terrain with a variety of flexibility. Github / Demo

The Terrain Generation

Terrain generation is based around a few key components, randomization, variation and interpolation. Upon creation, the grid is split into chunks, each that have matching corners with the chunks surrounding it. New corners are created based of the variation factor, this makes it so changes in elevation can be varied. For example, if one chunk has the top left corner a value of 1, the three other corners, with a variation factor of 1, can be either 0, 1 or 2. After the corners are determined the rest of the chunk is developed with interpolation. Interpolation makes it so there is a smooth transition in terrain from each corner of the chunk. After that, the map can be accessed as either a JSON or by pulling specific attributes from the map object. Data, such as, the whole map to one specific voxel on a certain chunk can be easily accessed.


Adding the map.js is as easy as importing any other JavaScript library or tool. Creating the map object is as straight forward as setting up an object. The first two inputs is the map size and the chunk size. Map size refers to the quantity of chunks on the x and y axis of the map and the chunk size refers to the quantity of voxels on the x and y axis of the chunk. The second two values refers the the minimum and maximum elevation that can be generated in a chunk. And finally, the last value is the variation factor of the map.

const map1 = new Map(5, 5, -3, 12, 0, 2)

And the output of map1.generate() would create an object with a generated map. The map can be generated multiple times with the same object. Other than using the JSON, the map object has built in functions like getChunk() and getVoxel().



The visual examples I have made use the terrain generator tool. It takes all of the values generated and draws them into a HTML canvas. This is one of the many possibilities for the tool. Although the tool is quite simple, it has many use cases to simple web-based game terrain generation to creating maps for table-top games. The example I created has the ability to easily change the quantity of chunks, colors of each elevation value and the variation factor.