【问题标题】:Threejs loading font using fontloader throws and error when using ReactThreejs在使用React时使用fontloader加载字体会抛出错误
【发布时间】:2019-01-04 13:10:30
【问题描述】:

我正在使用ThreeJS 库和React

我已经安装了 ThreeJS using npm

添加图像效果很好 - 我正在像这样导入图像:

import stockImage from './../../images/download.jpg';

像这样使用它效果很好:

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;
    }

尝试使用 this tutorial 向画布添加文本时。

我正在尝试像这样导入字体:

import helveticaRegular from './../../fonts/helvetiker_regular.typeface.json';

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

console.log(helveticaRegular);

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

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);
    } );

错误如下:

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

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

不知道是urls还是react还是ThreeJS中的FileLoader.load函数问题。

【问题讨论】:

  • 你试过直接使用字体路径吗?

标签: reactjs three.js


【解决方案1】:

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

FontLoader.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : null

您传入的是导入的文件,因此 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.

【讨论】:

  • 非常感谢!我不知道解析函数和“幕后”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);
猜你喜欢
  • 1970-01-01
  • 2016-03-30
  • 1970-01-01
  • 2018-12-02
  • 1970-01-01
  • 2023-04-03
  • 2019-11-10
  • 1970-01-01
  • 2020-03-10
相关资源
最近更新 更多