I've been experimenting with using the fetch
statement to fetch a local image and incorporate it into my (three.js) project. However, I seem to have created an infinite loop and I can't figure out why.
Since the project is quite large, I've included the relevant code snippet here:
var mesh;
function fetch_img(filename) {
fetch(filename).then(function(response) {
if (response.ok) {
return response.blob();
}
throw new Error('Network response was an error.');
}).then(function(blob) {
mesh.material.map.image.src = URL.createObjectURL(blob);
mesh.material.map.needsUpdate = true;
}).catch(function(error) {
console.log('Fetch failed because: ' + error.message);
});
}
function start() {
var material = new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load('loading.jpg', function(texture) {
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
fetch_img('test1.jpg');
})
});
}
The concept behind this implementation is to display a 'loading' image first, and then switch to the actual image once the scene is created and loaded. I plan to call fetch_img()
from multiple locations based on user input.
I suspect that my issue lies in my attempt to grasp JavaScript Promises. Can someone guide me in the right direction?