title: Calculate the vertex while creating terrain from heightmap using ThreeJs
body: <p>I'm reading "create terrain from heightmap" example from ThreeJs Cookbook</p>
  
  <p>This example load GrandCanyon:  <a href="http://lh5.ggpht.com/_-B0hFoGrn-w/SvHiYk39yAI/AAAAAAAABOQ/6IGZwifUYGA/GrandCanyon.png" rel="nofollow">http://lh5.ggpht.com/_-B0hFoGrn-w/SvHiYk39yAI/AAAAAAAABOQ/6IGZwifUYGA/GrandCanyon.png</a> </p>
  
  <p>And create a 3D terrain: <a href="http://www.smartjava.org/tjscb/02-geometries-meshes/02.06-create-terrain-from-heightmap.html" rel="nofollow">http://www.smartjava.org/tjscb/02-geometries-meshes/02.06-create-terrain-from-heightmap.html</a></p>
  
  <p>There are some code pieces I can not understand:</p>
  
  <pre><code>// draw on canvas
          ctx.drawImage(img, 0, 0);
          var pixel = ctx.getImageData(0, 0, width, depth);
  
          var geom = new THREE.Geometry;
          var output = [];
          for (var x = 0; x &lt; depth; x++) {
              for (var z = 0; z &lt; width; z++) {
                  // get pixel
                  // since we're grayscale, we only need one element
  
                  var yValue = pixel.data[z * 4 + (depth * x * 4)] / heightOffset;                       
                  var vertex = new THREE.Vector3(x * spacingX, yValue, z * spacingZ);
                  geom.vertices.push(vertex);
              }
          }
  </code></pre>
  
  <p>why is yValue calculated with that value ? why don't we use var yValue = pixel.data[z * 4 + (depth * x )] or something like that ?</p>
  
  <p>And do we really need spacingX and spacingZ ?</p>
  
  <p>Source code is here: <a href="https://github.com/josdirksen/threejs-cookbook/blob/master/02-geometries-meshes/02.06-create-terrain-from-heightmap.html" rel="nofollow">https://github.com/josdirksen/threejs-cookbook/blob/master/02-geometries-meshes/02.06-create-terrain-from-heightmap.html</a></p>
  
  <p>Could you please help me ?</p>
  
  <p>Thank you very much!</p>