如何在Three.js网格上创建矩形SVG网格作为纹理

时间:2019-02-17 09:55:42

标签: javascript svg three.js

如何在three.js网格上创建矩形的svg网格作为textur?网格可以具有动态尺寸。我希望svg纹理不要被拉伸,并保持其原始大小。

结果应该像这张图片上一样

以下是我目前的状态:https://jsfiddle.net/s7vjkLon/6/

您可以看到SVG(左上角)的大小为128px,并且在网格(底部)上未以其原始大小显示SVG。它被拉长了。

function init() {

  renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setClearColor(0xFFFFFF);
  document.body.appendChild(renderer.domElement);

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
  camera.position.z = 500;

	scene = new THREE.Scene();
  scene.add(camera);

}

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}

function createGridOnMesh(options) {

	var space = options.space;
  var meshWidth = options.meshWidth;
  var meshHeight = options.meshHeight;
  var lineWidth = 2;

  var canvas = document.getElementById('canvas');
  canvas.width = Math.pow(2, 7);
  canvas.height = Math.pow(2, 7);

  var context = canvas.getContext('2d');
  context.fillStyle = "rgba(0, 0, 0, 1)";
  context.fillRect(0, 0, canvas.width, canvas.height);

  context.fillStyle = "rgba(255, 0, 0)";
  context.fillRect(Math.round(lineWidth / 2), Math.round(lineWidth / 2), canvas.width - lineWidth, canvas.height - lineWidth);

  var texture = new THREE.CanvasTexture(canvas);
  texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
  texture.repeat.set(2, 2);   
  texture.needsUpdate = true;
  
  geometry = new THREE.BoxBufferGeometry(meshWidth, meshHeight, 200);
  material = new THREE.MeshBasicMaterial({ map: texture });
  mesh = new THREE.Mesh(geometry, material);

  scene.add( mesh );  

}


init();
animate();
createGridOnMesh({ space: 20, meshWidth: 600, meshHeight: 200})
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/101/three.min.js"></script>
<canvas id="canvas"></canvas>

谢谢。

0 个答案:

没有答案