在Three.js中挤出2D彩色图像

时间:2020-03-29 19:25:58

标签: javascript svg three.js 3d rendering

我一直在网上寻找资源,但是还没有找到在Three.js中拉伸彩色图像的方法。我正在尝试创建类似Minecraft物品的东西,其中使用图像来创建挤压的几何形状。例如:https://minecraft.gamepedia.com/File:BowSpinning3.gif

我尝试查看以下资源:https://muffinman.io/three-js-extrude-svg-path/,但这只会挤出未着色的SVG。


loader.load('./textures/diamondbleu.svg', function (data) {

  // Group we'll use for all SVG paths
  const svgGroup = new THREE.Group();
  // When importing SVGs paths are inverted on Y axis
  // it happens in the process of mapping from 2d to 3d coordinate system
  svgGroup.scale.y *= -1;

  const material = new THREE.MeshLambertMaterial();

  // Loop through all of the parsed paths
  data.paths.forEach((path, i) => {
    const shapes = path.toShapes(true);

    // Each path has array of shapes
    shapes.forEach((shape, j) => {
      // Finally we can take each shape and extrude it
      const geometry = new THREE.ExtrudeGeometry(shape, {
        depth: 20,
        bevelEnabled: false
      });

      // Create a mesh and add it to the group
      const mesh = new THREE.Mesh(geometry, material);

      svgGroup.add(mesh);
    });
  });

  // Get group's size
  const box = new THREE.Box3().setFromObject(svgGroup);
  const size = new THREE.Vector3();
  box.getSize(size);

  const yOffset = size.y / -2;
  const xOffset = size.x / -2;

  // Offset all of group's elements, to center them
  svgGroup.children.forEach(item => {
    item.position.x = xOffset;
    item.position.y = yOffset;
  });

  svgGroup.position.set(0, blockSize*75, 0);

  // Finally we add svg group to the scene
  scene.add(svgGroup);
})

有没有一种方法可以修改代码以允许使用彩色SVG?谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用"examples/jsm/loaders/"文件夹中的SVGLoader

文档概述了how to generate SVGs in 3D space,看来您的代码示例缺少paths循环制作新材料并为每个path分配颜色的部分:

var material = new THREE.MeshBasicMaterial( {
    color: path.color,
    side: THREE.DoubleSide,
    depthWrite: false
} );

您的代码似乎创建了一个LambertMaterial,没有分配颜色,也没有灯光。 Lambert材质需要照亮灯光,而BasicMaterial仅显示颜色而无需灯光。

再看at the code in this demo。该演示不使用path.color,而是通过访问path.userData.style.fill来查找颜色。我认为您会希望使用后一种方法,具体取决于您的SVG文件。

相关问题