我加载图像以显示精灵。
但似乎代码在图像完全加载之前进行:
但我不知道如何使用Threejs等待图像完全加载。 我可以帮忙吗?
可以在此处测试代码:http://www.planetarium2016.com/sprite.html
这是我的代码:
<html>
<head>
<title>My first three.js app</title>
<style>
body { margin: 0; }
canvas { width: 100%; height: 100% }
</style>
</head>
<body>
<script src="https://rawgithub.com/mrdoob/three.js/master/build/three.js"></script>
<script>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 500);
camera.position.set(0, 10, 100);
camera.lookAt(new THREE.Vector3(0, 0, 0));
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var material = new THREE.LineBasicMaterial({ color: 0x0000ff });
var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(-10, 0, 0));
geometry.vertices.push(new THREE.Vector3(0, 10, 0));
geometry.vertices.push(new THREE.Vector3(10, 0, 0));
geometry.vertices.push(new THREE.Vector3(0, 0, -10));
var line = new THREE.Line(geometry, material);
scene.add(line);
var loader = new THREE.TextureLoader();
var spriteMap = loader.load("https://codefisher.org/static/images/pastel-svg/256/bullet-star.png");
//+-----------------------------------------------------------+
//| I need here to wait for the image to be fully loaded |
//| This cheat is fool: while (spriteMap.image.width == 0); |
//+-----------------------------------------------------------+
var spriteMaterial = new THREE.SpriteMaterial( { map: spriteMap, color: 0xffffff } );
var sprite = new THREE.Sprite( spriteMaterial );
sprite.scale.set(256, 256, 1);
sprite.position.set( 0, 0, 10 );
scene.add( sprite );
//camera.position.z = 2;
var render = function () {
requestAnimationFrame( render );
renderer.render(scene, camera);
};
render();
</script>
</body>
</html>
THREE JS TextureLoader有点旧......
答案 0 :(得分:0)
解决方案:https://threejs.org/docs/#api/loaders/TextureLoader
这是解决我问题的代码:
var url = "https://codefisher.org/static/images/pastel-svg/256/bullet-star.png";
var loader = new THREE.TextureLoader();
var spriteMaterial;
loader.load(url,
function(texture)
{
spriteMaterial = new THREE.SpriteMaterial( { map: texture, color: 0x0000ff } );
}
);
var sprite = new THREE.Sprite( spriteMaterial );
答案 1 :(得分:0)
var loader = new THREE.TextureLoader();
loader.load(
'img/url/img.png',
function ( map ) {
// map var is your image
},
function ( xhr ) {
if ( xhr.lengthComputable ) {
console.log( 'percent: ' + (xhr.loaded / xhr.total * 100) );
}
},
function ( err ) {
console.log( 'An error happened' );
}
);
三点73