使用 React 时 Threejs 使用 fontloader 加载字体会抛出错误

Pet*_*sen 1 three.js reactjs

我将ThreeJS库与React一起使用。

我已经使用 npm安装了 ThreeJS 。

添加图像工作正常 - 我正在像这样在反应中导入图像:

import stockImage from './../../images/download.jpg';
Run Code Online (Sandbox Code Playgroud)

像这样使用它效果很好:

this.addCube(stockImage, { x:2, y:2, z:2 } );

(...)

addCube(imageUrl, aPosition) {
        //Load image as material:
        var anImageMaterial = new THREE.MeshBasicMaterial({
            map : this.textureLoader.load(imageUrl)
        });
        //Make box geometry:
        var box = new THREE.BoxGeometry( 1, 1, 1 );
        //Create mesh:
        var cube = new THREE.Mesh( box, anImageMaterial );
        //Add to scene:
        this.scene.add( cube );
        return cube;
    }
Run Code Online (Sandbox Code Playgroud)

尝试使用本教程将文本添加到画布时。

我正在尝试以如下方式导入字体:

import helveticaRegular from './../../fonts/helvetiker_regular.typeface.json';
Run Code Online (Sandbox Code Playgroud)

像这样打印看起来不错,所以用react好像不是问题:

console.log(helveticaRegular);
Run Code Online (Sandbox Code Playgroud)

但是使用这样的字体会引发错误:

var loader = new THREE.FontLoader();

loader.load( helveticaRegular, function ( font ) {
        var geometry2 = new THREE.TextGeometry( 'Hello three.js!', {
            font: font,
            size: 80,
            height: 5,
            curveSegments: 12,
            bevelEnabled: true,
            bevelThickness: 10,
            bevelSize: 8,
            bevelSegments: 5
        } );
        this.scene.add(geometry2);
    } );
Run Code Online (Sandbox Code Playgroud)

错误如下:

在此处输入图片说明

在此处输入图片说明

请忽略 C:/xammp/... 因为我没有使用 xammp,但文件夹命名是从我使用 xammp 时开始的。

使用 xammp 加载这样的字体,使用常规 url 不会产生相同的错误。

我不知道问题是由于urls还是react还是ThreeJS中的FileLoader.load函数引起的。

Mos*_*ini 5

FontLoader 需要一个 URL 作为签名参数:

FontLoader.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : null
Run Code Online (Sandbox Code Playgroud)

您传入的是导入的文件,因此 FontLoader.load 不喜欢它,因为幕后会有一个带有 url 参数的 xhr 调用

可能正确的方法是跳过加载阶段并继续 FontLoader.parse(myImportedFont)

FontLoader.parse 签名

.parse ( json : Object ) : Font
json — The JSON structure to parse.

Parse a JSON structure and return a Font.
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢!我不知道解析函数和“幕后”xhr 调用。以下代码有效: var loader = new THREE.FontLoader(); var font = loader.parse(helveticaRegular); var textGeometry = new THREE.TextGeometry('Hello Three.js!', { font: font, size: 1, height: 0.1, curveSegments: 20 } ); var textMaterial = new THREE.MeshBasicMaterial( { color: 0xF00000 } ); var textMesh = new THREE.Mesh( textGeometry, textMaterial ); this.scene.add(textMesh); (2认同)