fontloader 和 textgeometry 在 threejs 中不起作用

fontloader and textgeometry not working in threejs

我需要在我的 threejs 项目中渲染一些文本,但是每次我添加模块时

import { FontLoader } from 'https://threejs.org/examples/jsm/loaders/FontLoader.js';
import { TextGeometry } from 'https://threejs.org/examples/jsm/geometries/TextGeometry.js';

抛出此错误

Uncaught TypeError: Error resolving module specifier “three”. Relative module specifiers must start with “./”, “../” or “/”. FontLoader.js:5:7

来自 FontLoader.js。如果我不包含其中任何一个,则三个 js 渲染场景并且工作正常。在我的网络日志中,它运行完美,所有模块都是 200 OK。

您必须使用最新 three.js 版本的导入地图。此外,永远不要直接从 https://threejs.org 导入模块。始终使用如下 CDN:

<script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>

<script type="importmap">
    {
        "imports": {
            "three": "https://unpkg.com/three@0.138.3/build/three.module.js"
        }
    }
</script>

<script type="module">

    import * as THREE from 'three';

    import { FontLoader } from 'https://unpkg.com/three@0.138.3/examples/jsm/loaders/FontLoader.js';
    import { TextGeometry } from 'https://unpkg.com/three@0.138.3/examples/jsm/geometries/TextGeometry.js';

Firefox 和 Safari 当前需要 polyfill es-module-shims.js

您收到的错误是因为您正在导入 JS 示例文件,这些文件实际上是 ESM 模块,但在其中包含来自 three 的无法解析的导入。

ThreeJS 导出 FontLoaderTextGeometry 所以你只需要从 CDN 导入 EcmaScript 模块 (ESM) 即可导入,例如:

import { FontLoader, TextGeometry } from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.module.js';

通过这种方式,它们将在 Chrome 中可用。