我正在尝试在 Three.js 中加载字体,到目前为止这非常困难。希望某人能在这件事上提供帮助。
我尝试使用 javascript 字体,就像《掌握三.js》一书中所建议的那样。书中的版本有效。我必须升级到 Three.js 的最新版本,但由于另一个原因,本书中的字体不适用于最新的 Three.js 版本。所以我尝试通过https://gero3.github.io/facetype.js/将 Three.js 的 json 字体转换为 js-fonts ,但这不起作用,因为当我按下转换按钮时,网站不会执行任何操作。
然后我尝试使用 FontLoader 来了解最新 Three.js 版本中的一些示例。由于 FontLoader 不返回任何内容,因此我很难获取字体。因此,尝试将字体分配给传递给 FontLoader 的函数中的全局变量 myfont。然而,当我执行 loader.load(...) 时,该函数不会被调用,但在我的代码中,只有当我放在此处的代码片段的最后一行被执行时,该函数才会被调用。即我事先在代码中发现错误。为什么代码只在那时执行而不是在我加载字体时执行,是否有充分的理由?
干杯汤姆
var loader = new THREE.FontLoader();
loader.load( 'three.js-master/examples/fonts/helvetiker_regular.typeface.json', function ( font ) {
init( font );
} );
var myfont;
function init( font ) {
myfont = font;
console.log("inner value "+myfont);
}
console.log("2nd time" +myfont);
var params = {
material: 0,
extrudeMaterial: 1,
bevelEnabled: false,
bevelThickness: 8,
bevelSize: 4,
font: myfont,
weight: "normal",
style: "normal",
height: 0,
size: 11,
curveSegments: 4
};
var textGeo = new THREE.TextGeometry("3D text", params);
console.log("3rd time "+myfont);
textGeo.computeBoundingBox();
console.log("4th time "+myfont);
textGeo.computeVertexNormals();
console.log("5th time "+myfont);
var material = new THREE.MeshFaceMaterial([
new THREE.MeshPhongMaterial({color: 0xff22cc, shading: THREE.FlatShading}), // front
new THREE.MeshPhongMaterial({color: 0xff22cc, shading: THREE.SmoothShading}) // side
]);
console.log("6th time "+myfont);
var textMesh = new THREE.Mesh(textGeo, material);
console.log("7th time "+myfont);
textMesh.position.x = -textGeo.boundingBox.max.x / 2;
textMesh.position.y = -5;
textMesh.position.z = 30;
textMesh.name = 'text';
scene.add(textMesh);
console.log("8th time "+myfont);
camControl = new THREE.OrbitControls(camera, renderer.domElement);
var geometry = new THREE.BoxGeometry( 70, 70, 70 );
var texture = THREE.ImageUtils.loadTexture('wallpaper.jpg');
var mainMaterial = new THREE.MeshBasicMaterial({
map:texture,
side:THREE.DoubleSide
});
console.log("9th time "+myfont);
var nonMainMaterial = new THREE.MeshBasicMaterial( { color: 0xcccccc } );
var materials = [mainMaterial, nonMainMaterial,nonMainMaterial,nonMainMaterial,nonMainMaterial,nonMainMaterial];
var meshFaceMaterial = new THREE.MeshFaceMaterial( materials );
console.log("10th time "+myfont);
var cube = new THREE.Mesh( geometry, meshFaceMaterial );
console.log("11th time "+myfont);
scene.add( cube );
console.log("12th time "+myfont);
var cubeBSP = new ThreeBSP(cube);
console.log("13th time "+myfont);
var textBSP = new ThreeBSP(textMesh);
console.log("14th time "+myfont);
var resultBSP = cubeBSP.subtract(textMesh);
Run Code Online (Sandbox Code Playgroud)
小智 3
FontLoader() 在底层使用了 XHRLoader。我的理解是,从代码来看,它是一个异步函数,其中回调函数是在“load”事件上执行的。加载需要时间,因此其余代码将在字体加载完成之前执行。将其余代码移至 init() 函数中,它应该可以工作。
| 归档时间: |
|
| 查看次数: |
3676 次 |
| 最近记录: |