The ImageLoader.load()
method is used in the Three.js library to load image resources asynchronously. This method is used to load textures, materials, and other images used in WebGL graphics.
ImageLoader.load(url: string, onLoad: Function, onProgress?: Function, onError?: Function): HTMLImageElement
url
: The URL of the image resource to be loaded.onLoad
: A function to be called when the image resource has finished loading.onProgress
(Optional): A function to be called during the loading process.onError
(Optional): A function to be called if the loading process fails.ImageLoader.load()
returns an HTMLImageElement
object.
const loader = new THREE.ImageLoader();
// Load a texture from a URL.
loader.load(
'https://example.com/example_texture.jpg',
function (image) {
const texture = new THREE.Texture(image);
// Use the texture in your Three.js scene.
},
function (xhr) {
console.log(`${(xhr.loaded / xhr.total) * 100}% loaded`);
},
function (error) {
console.error('Error occurred while loading texture:', error);
}
);
const scene = new THREE.Scene();
const renderer = new THREE.WebGLRenderer();
document.body.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
1,
1000
);
camera.position.set(0, 0, 5);
const loader = new THREE.ImageLoader();
// Load a texture from a URL.
loader.load(
'https://i.imgur.com/KMHPMnR.jpg',
function (image) {
const texture = new THREE.Texture(image);
// Create a plane geometry.
const geometry = new THREE.PlaneGeometry(2, 2);
// Create a material with the texture mapped to the plane.
const material = new THREE.MeshBasicMaterial({ map: texture });
// Create a mesh with the geometry and material.
const mesh = new THREE.Mesh(geometry, material);
// Add the mesh to the scene.
scene.add(mesh);
},
function (xhr) {
console.log(`${(xhr.loaded / xhr.total) * 100}% loaded`);
},
function (error) {
console.error('Error occurred while loading texture:', error);
}
);
// Render loop.
function render() {
renderer.render(scene, camera);
requestAnimationFrame(render);
}
render();
ImageLoader.load()
can load any image format the browser supports (PNG, JPEG, GIF, etc.).onLoad
callback receives an HTMLImageElement
object as its only argument. This object can be used to create a THREE.Texture
object or any other WebGL texture.onProgress
callback receives an XMLHttpRequestProgressEvent
object as its only argument, which provides information about the loading progress.onError
callback receives an ErrorEvent
object as its only argument, which provides information about the loading error.