如何在Three.js中的OBJ文件上应用SVG纹理

时间:2019-12-05 06:18:14

标签: svg three.js texture-mapping texture2d objloader

我正在为我的项目使用 Threejs ,我使用OBJ加载器渲染了一个对象文件,它在屏幕上显示了该对象。但是我不知道如何将SVG图像映射到该对象,以及如何在该对象文件上应用纹理。 请帮助我,这是我当前的代码。 我是这个平台的新手,对THREE.js不太了解,我已经看到了一些示例,但对我而言却没有奏效。 我最近发布的帖子中的一个人告诉我如何在对象上应用材质,但对我没有用。

应用材料时出现此错误。 ERROR TypeError: Cannot set property 'map' of undefined

这是我完整的代码文件。

import { Component, AfterViewInit, ViewChild, Input, ElementRef } from '@angular/core';
import * as THREE from 'three';
import { OrbitControls } from '@avatsaev/three-orbitcontrols-ts';
import {OBJLoader} from 'three-obj-mtl-loader';
import { TextureLoader } from 'three';



@Component({
  selector: 'app-scene',
  templateUrl: './scene.component.html',
  styleUrls: ['./scene.component.css']
})
export class SceneComponent implements AfterViewInit {
  @Input() name: string;
  @ViewChild('canvas', {static:true}) canvasRef: ElementRef;


  renderer = new THREE.WebGLRenderer;
  scene = null;
  camera = null;
  controls = null;
  mesh = null;
  light = null;
  loader;
  svgLoader;
  private calculateAspectRatio(): number {
    const height = this.canvas.clientHeight;
    if (height === 0) {
      return 0;
    }
    return this.canvas.clientWidth / this.canvas.clientHeight;
  }

  private get canvas(): HTMLCanvasElement {
    return this.canvasRef.nativeElement;
  }

  constructor() {
    // this.loader = new OBJLoader();
    this.scene = new THREE.Scene();
    this.loader = new OBJLoader();

    this.camera = new THREE.PerspectiveCamera(15, window.innerWidth / window.innerHeight, 0.1, 1000)
  }

  ngAfterViewInit() {
    this.configScene();
    this.configCamera();
    this.configRenderer();
    this.configControls();
    this.createLight();
    this.createMesh();
    this.animate();
  }

  configScene() {
    // this.scene.background = new THREE.Color( 0xdddddd );
  }

  configCamera() {
    this.camera.aspect = this.calculateAspectRatio();
    this.camera.updateProjectionMatrix();
      this.camera.position.set( 0, 0, 3 );
      this.camera.lookAt( this.scene.position );
  }

  configRenderer() {
    this.renderer = new THREE.WebGLRenderer({
      canvas: this.canvas,
      antialias: true,
      alpha: true
    });
    this.renderer.setPixelRatio(devicePixelRatio);

    // setClearColor for transparent background
    // i.e. scene or canvas background shows through
    this.renderer.setClearColor( 0x000000, 0 );
    this.renderer.setSize((window.innerWidth/2), (window.innerHeight/2));
    window.addEventListener('resize', ()=>{
      this.renderer.setSize((window.innerWidth/2), (window.innerHeight)/2);
      this.camera.aspect = window.innerWidth / window.innerHeight;
      this.camera.updateProjectionMatrix();
    })
    console.log('clientWidth', this.canvas.clientWidth);
    console.log('clientHeight', this.canvas.clientHeight);
  }

  configControls() {
    this.controls = new OrbitControls(this.camera);
    this.controls.autoRotate = false;
    this.controls.enableZoom = false;
    // this.controls.maxDistance = 5;
    // this.controls.minDistance = 10;
    this.controls.enablePan = false;
    this.controls.update();
  }


  createLight() {
    this.light = new THREE.PointLight( 0xffffff );
      this.light.position.set( -10, 10, 10 );
      this.scene.add( this.light );
  }

  createMesh() {
      const url ='../../../../assets/abc.svg';


        this.loader.load('../../../../assets/nonunified.obj', (object)=>{

            object.traverse( function ( child ) {
              if ( child instanceof THREE.Mesh ) {
                  child.geometry.center();
              }
            } );
            object.material.map = new TextureLoader().load(url)
            this.scene.add(object)
          },
            // called when loading is in progresses
            function (xhr) {

            console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );

          },
        // called when loading has errors
            function ( error ) {
            console.log( 'An error happened' );

          }
        )}

  animate() {
    window.requestAnimationFrame(() => this.animate());
    this.controls.update();
    this.renderer.render(this.scene, this.camera);
  }

}

1 个答案:

答案 0 :(得分:0)

您尚未创建材料。如果您执行console.log(object.material);它将显示未定义。您首先需要创建一种材料。请检查threejs文档以了解可以使用的不同材料。对于此示例,我使用的是MeshPhongMaterial。因此,您的createMesh函数将如下所示。

createMesh() {
        const url = '../../../../assets/abc.svg';

        this.loader.load('../../../../assets/nonunified.obj', (object) => {

            object.traverse(function (child) {
                if (child instanceof THREE.Mesh) {
                    child.geometry.center();
                }
            });

            const material = new THREE.MeshPhongMaterial({
                map: new TextureLoader().load(url)
            });

            object.material = material;

            this.scene.add(object)
        },
            // called when loading is in progresses
            function (xhr) {

                console.log((xhr.loaded / xhr.total * 100) + '% loaded');

            },
            // called when loading has errors
            function (error) {
                console.log('An error happened');

            }
        )
    }

这应该有效。