无法在Three.js中将纹理映射到网格

时间:2018-06-27 13:31:02

标签: javascript html three.js 3d

我一直在努力构建一个非常简单的程序,该程序将在three.js中根据图像和该图像的纹理创建高度图

经过一些修改后,我可以很容易地从图像生成高度图/网格,但无法将纹理映射到该网格对象。尽管可以确定它在addMesh();函数中,但是我不确定哪里出错了。这是我对three.js的首次尝试,因此很明显。

我抛出的错误是:

  

三。材料:“地图”参数未定义。

这是呈现的内容:

This is what is rendered

这是我正在使用的代码:

// Define variables
var camera, scene, renderer, geometry, material, mesh;
var img = document.getElementById("landscape-image");
var texture = new THREE.TextureLoader().load( "assets/texture.png" )

// Get the pixels by draw the image onto a canvas. From the canvas get the Pixel (R,G,B,A)
function getTerrainPixelData(){
  var canvas = document.getElementById("canvas");

  canvas.width = img.width;
  canvas.height = img.height;
  canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

  var data = canvas.getContext('2d').getImageData(0,0, img.height, img.width).data;
  var normPixels = []
  for (var i = 0, n = data.length; i < n; i += 4) {
    // get the average value of R, G and B.
    normPixels.push((data[i] + data[i+1] + data[i+2]) / 3); //Essentially render image black and white
  }

  return normPixels;
}

// Create a mesh from pixel data
function addMesh() {

  var numSegments = img.width-1; //Equal to number of image pixels - 1

  geometry = new THREE.PlaneGeometry(2400, 2400, numSegments, numSegments);

  material = new THREE.MeshBasicMaterial({
    wireframe: true,
    map: texture
  });

  terrain = getTerrainPixelData();

  for (var i = 0, l = geometry.vertices.length; i < l; i++) // For each vertex
  {
    var terrainValue = terrain[i] / 255;
    geometry.vertices[i].z = geometry.vertices[i].z + terrainValue * 800 ; // Define height of vertices against image pixel data
  }

  mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh)
}

// Function to render scene and camera
function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}

scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 10000); //Field-of-View, Aspect Ratio, Near Render, Far Render
camera.position.z = 3000; // Camera distance

renderer = new THREE.WebGLRenderer();
controls = new THREE.OrbitControls( camera, renderer.domElement );

addMesh();

renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

render();
body {
  margin: 0;
}

#canvas {
  display: none;
}

#assets {
  display: none;
}
<html>
<head>
  <title>Landscape Test</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div id="assets"><img id="landscape-image" src="assets/Heightmap2.png"/></div>
  <canvas id="canvas"></canvas>
  <script src="js/three.min.js"></script>
  <script src="js/OrbitControls.js"></script> <!-- added so user can rotate the scene with the mouse -->
  <script src="js/app.js"></script>
</body>
</html> 

0 个答案:

没有答案