Perlin Noise Terrain Visualization
Contains class for generating Perlin Noise
HTML
<div id="container">
<input id='seed' type='number' value='1288090'>Seed:</input><br/>
<canvas id="canvas" width="250" height="250">
</canvas>
<div style="float: left;">
<input type='button' value='Start' onclick="javascript:Start();"></input><br />
<input type='button' value='Stop' onclick="javascript:Stop();"></input><br />
<input type='button' value='Reset' onclick="javascript:Reset();"></input>
</div>
</div>
<img src="http://jsfiddle.net/img/logo.png" onload="javascript:Reset();"></img>
CSS
#canvas {
border: solid 1px black;
float: right;
}
#container{
width:215px;
}
input[type=button]{
width:70px;
}
input[type=number]{
float:right;
}
img{
display:none;
}
JavaScript
// This is where the magic happens
// We generate the terrain in this function.
// ===========================================
var UpdateImg = function(id){
// Book-keeping, only needed for this specific sim
if(z == 128){
running = false;
clearInterval(myTimer);
return;
}
var canvas = document.getElementById(id);
var width = canvas.width;
var height = canvas.height;
var ctx = canvas.getContext('2d');
var imgData = ctx.getImageData(0,0,width,height);
var wDiv = 1 / width;
var hDiv = 1 / height;
var zDiv = 1 / 128;
for(var i = 0; i < imgData.data.length; i += 4){
var x = (i / 4) % width;
var y = (i / 4) / width;
// And here is the crux of the algorithm
// 8 Octaves of noise
// Octave value = Amplitude * Noise(freq * x, freq * y, freq * z)
//
// Fractional values are desired for (x,y,z) in order to not cluster at integer values
// Integer values = one big block of nothing
//
// Note: negative frequency values do some really weird things...don't really recommend it
// unless you know what you're doing with it. But it can be interesting.
// We can warp the coordinates before the noise lookup for less isomorphic terrain
//
//var warp = 8 * noise.Noise(2 * x * wDiv, 2 * y * hDiv, 2 * z * zDiv);
//x += warp;
//y += warp;
//z += warp;
var density = 64 * noise.Noise(4 * x * wDiv, 4 * y * hDiv, z * zDiv) +
32 * noise.Noise(8 * x * wDiv, 8 * y * hDiv, z * zDiv) +
16 * noise.Noise(16 * x * wDiv, 16 * y * hDiv, z * zDiv) +
8 * noise.Noise(32 * x * wDiv, 32 * y * hDiv, z * zDiv) +
4 * noise.Noise(64 * x * wDiv, 64 * y * hDiv, z * zDiv) +
2 * noise.Noise(128 * x * wDiv, 128 * y * hDiv, z * zDiv);
...