Use SVG as Texture in Three.js

This article provides a direct, step-by-step guide on how to load and apply an external SVG file as a texture onto 3D surfaces in Three.js. Instead of parsing the SVG into complex 3D vector paths using SVGLoader, you will learn how to render the SVG as a 2D image map, preserving the original design assets while keeping rendering performance optimal.

Method 1: The Direct TextureLoader Approach

The most straightforward way to use an SVG as a texture is by loading it directly using THREE.TextureLoader. Since modern web browsers natively rasterize SVG files, Three.js can process an SVG file just like a standard PNG or JPEG.

import * as THREE from 'three';

// Initialize the texture loader
const textureLoader = new THREE.TextureLoader();

// Load the external SVG file
const svgTexture = textureLoader.load('path/to/your/file.svg', (texture) => {
    // Optional: Configure texture filtering for better rendering
    texture.minFilter = THREE.LinearFilter;
    texture.generateMipmaps = false;
});

// Create a material using the SVG texture
const material = new THREE.MeshStandardMaterial({
    map: svgTexture,
    transparent: true // Enable transparency if the SVG has a transparent background
});

// Apply the material to a 3D surface
const geometry = new THREE.PlaneGeometry(5, 5);
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

Method 2: The CanvasTexture Approach (For Maximum Crispness)

When using TextureLoader, the browser rasterizes the SVG at its default defined size, which can sometimes result in a blurry texture when viewed up close in 3D space. To control the resolution and ensure a crisp render, you can draw the SVG onto an offscreen HTML <canvas> at a higher resolution before converting it into a THREE.CanvasTexture.

import * as THREE from 'three';

const width = 1024;  // Target width of the texture
const height = 1024; // Target height of the texture

const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d');

const img = new Image();
img.src = 'path/to/your/file.svg';

// Create a canvas texture
const canvasTexture = new THREE.CanvasTexture(canvas);

img.onload = () => {
    // Draw the SVG onto the canvas at high resolution
    context.clearRect(0, 0, width, height);
    context.drawImage(img, 0, 0, width, height);
    
    // Tell Three.js to update the texture with the new canvas data
    canvasTexture.needsUpdate = true;
};

// Apply to your 3D mesh
const material = new THREE.MeshBasicMaterial({
    map: canvasTexture,
    transparent: true
});
const geometry = new THREE.BoxGeometry(2, 2, 2);
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

Important Considerations