title: Load Textures description: Add texture maps to your TresJS objects. author: alvarosabu thumbnail: /recipes/load-textures.png
All textures used in this example are from ambientcg.
Three-dimensional (3D) textures are images that contain multiple layers of data, allowing them to represent volume or simulate three-dimensional structures. These textures are commonly used in 3D graphics and visual effects to enhance the realism and complexity of scenes and objects.
There are two ways of loading 3D textures in TresJS:
::: warning
Please note that in the examples below use top level await
. Make sure to wrap such code with a Vue's Suspense component.
:::
useLoader
The useLoader
composable allows you to pass any type of three.js loader and a URL to load the resource from. It returns a Promise
with the loaded resource.
For a detailed explanation of how to use useLoader
, check out the useLoader documentation.
import { useLoader } from '@tresjs/core'
import { Texture, TextureLoader } from 'three'
const { state: texture, isLoading } = useLoader(
TextureLoader,
'/Rock035_2K_Color.jpg',
)
Then you can pass the texture to a material:
::: code-group
<script setup lang="ts">
import TexturedSphere from './TexturedSphere.vue'
</script>
<template>
<TresCanvas
clear-color="#82DBC5"
shadows
alpha
>
<Suspense>
<TexturedSphere />
</Suspense>
</TresCanvas>
</template>
<script setup lang="ts">
import { useLoader } from '@tresjs/core'
import { TextureLoader } from 'three'
const { state: texture, isLoading } = useLoader(
TextureLoader,
'/Rock035_2K_Color.jpg',
{
initialValue: new Texture(),
},
)
</script>
<template>
<TresMesh>
<TresSphereGeometry :args="[1, 32, 32]" />
<TresMeshStandardMaterial :map="texture" />
</TresMesh>
</template>
:::
::: tip
To avoid using v-if on the material, you can set a default texture as the initial value of the state
property.
:::
useTexture
A more convenient way of loading textures is using the useTexture
and useTextures
composables from the @tresjs/cientos
package.
To learn more about useTexture
, check out the useTexture documentation.
import { useTexture } from '@tresjs/cientos'
const { state: texture, isLoading } = useTexture('/Rock035_2K_Color.jpg')
Similar to the previous example, we can pass all the textures to a material via props:
<TresMesh>
<TresSphereGeometry :args="[1,32,32]" />
<TresMeshStandardMaterial :map="texture" />
</TresMesh>