I’m trying to use the Midpoint Displacement Algorithm using JavaScript and canvas as recommended on gamedev.stackexchange.com.
The code below generates points where the array index is the x position and its value is the y position.
var createTerrain = function(chops, range) {
chops = chops || 2;
range = parseInt(range || 100);
if (chops > 8) return;
var cycle = parseInt(width / chops);
for (var i = 0; i <= width; i += cycle) {
var y = (height / 2) + getRandomNumber(-range, range);
terrain[i] = y;
}
chops *= 2;
range *= 0.5;
createTerrain(chops, range);
}
getRandomNumber()‘s arguments are min and max. width and height are respective of the canvas.
This produces something like…

It seems pretty choppy, but that may just be how it is.
Have I got this algorithm right? If not, what is wrong, and can you point me in the right direction?
I’d say it does not look like mid-point displacement, simply because every segment should be getting a regular X axis length (you have nearly vertical segments). Have you tried to generate a simple 4-segment array? What does it look like?
Here is a short tutorial I wrote, you can see it in action: Mid-point algorithm in Javascript
The source code: