You can edit the below JavaScript code to customize the image tool.
Apply Changes
async function processImage(originalImg, depth = 15, resolution = 256, wireframe = 'false', bgColor = '#000000') {
// Return a container that matches the prompt's requirement for a single element
const container = document.createElement('div');
container.style.width = '100%';
container.style.height = '600px';
container.style.position = 'relative';
container.style.overflow = 'hidden';
container.style.backgroundColor = bgColor;
// Add loading text while we fetch Three.js
const loadingMessage = document.createElement('div');
loadingMessage.textContent = 'Generating 3D Mesh...';
loadingMessage.style.position = 'absolute';
loadingMessage.style.top = '50%';
loadingMessage.style.left = '50%';
loadingMessage.style.transform = 'translate(-50%, -50%)';
loadingMessage.style.color = 'white';
loadingMessage.style.fontFamily = 'sans-serif';
container.appendChild(loadingMessage);
// Load Three.js core dynamically
if (!window.THREE) {
await new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/three@0.128.0/build/three.min.js';
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
// Load OrbitControls dynamically
if (!window.THREE.OrbitControls) {
await new Promise((resolve, reject) => {
const script = document.createElement('script');
// Utilizing the old /js/ directory up to r128 to avoid raw ES module import issues from standard file paths
script.src = 'https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js';
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
const THREE = window.THREE;
container.removeChild(loadingMessage); // remove loader once ready
// 1. Prepare textures: a color map, and a grayscale displacement map
const mapCanvas = document.createElement('canvas');
mapCanvas.width = originalImg.width;
mapCanvas.height = originalImg.height;
const mCtx = mapCanvas.getContext('2d');
mCtx.drawImage(originalImg, 0, 0);
const heightCanvas = document.createElement('canvas');
heightCanvas.width = originalImg.width;
heightCanvas.height = originalImg.height;
const hCtx = heightCanvas.getContext('2d');
hCtx.drawImage(originalImg, 0, 0);
try {
// Build grayscale luminance map for proper 3D elevation
const imgData = hCtx.getImageData(0, 0, heightCanvas.width, heightCanvas.height);
for (let i = 0; i < imgData.data.length; i += 4) {
const lum = 0.299 * imgData.data[i] + 0.587 * imgData.data[i + 1] + 0.114 * imgData.data[i + 2];
imgData.data[i] = lum;
imgData.data[i + 1] = lum;
imgData.data[i + 2] = lum;
}
hCtx.putImageData(imgData, 0, 0);
} catch (e) {
console.warn("CORS issue: Could not manipulate image pixels. The mesh will use standard channel displacement.");
}
const colorTexture = new THREE.CanvasTexture(mapCanvas);
const displacementTexture = new THREE.CanvasTexture(heightCanvas);
// 2. Compute mesh geometry dimensions to maintain aspect ratio safely
const aspect = originalImg.width / originalImg.height;
let planeWidth = 100;
let planeHeight = 100 / aspect;
if (aspect < 1) {
planeHeight = 100;
planeWidth = 100 * aspect;
}
// Keep vertex count safe and performant
const safeResolution = Math.max(10, Math.min(Number(resolution) || 256, 512));
let segX = Math.round(safeResolution);
let segY = Math.round(safeResolution / aspect);
if (aspect < 1) {
segY = Math.round(safeResolution);
segX = Math.round(safeResolution * aspect);
}
// 3. Initialize Three.js scene
const scene = new THREE.Scene();
try {
scene.background = new THREE.Color(bgColor);
} catch (e) {
scene.background = new THREE.Color('#000000');
}
const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(window.devicePixelRatio || 1);
container.appendChild(renderer.domElement);
const isWireframe = String(wireframe).toLowerCase() === 'true';
const depthScale = Number(depth) || 15;
// Apply the extracted maps to the standard material
const material = new THREE.MeshStandardMaterial({
map: colorTexture,
displacementMap: displacementTexture,
displacementScale: depthScale,
wireframe: isWireframe,
side: THREE.DoubleSide
});
const geometry = new THREE.PlaneGeometry(planeWidth, planeHeight, segX, segY);
const mesh = new THREE.Mesh(geometry, material);
// Tilt back slightly for an immediate 3D-feeling impression
mesh.rotation.x = -Math.PI / 4;
scene.add(mesh);
// 4. Lighting setup for nice shadows on the ridges
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const mainLight = new THREE.DirectionalLight(0xffffff, 0.8);
mainLight.position.set(20, 100, 100);
scene.add(mainLight);
// Position camera dynamically based on scaled geometry
camera.position.z = Math.max(planeWidth, planeHeight) * 1.4;
camera.position.y = Math.max(planeWidth, planeHeight) * 0.4;
camera.lookAt(0, 0, 0);
// Allow user interactions
const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
// 5. Setup Viewport + Responsiveness
const resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
const { width, height } = entry.contentRect;
if (width > 0 && height > 0) {
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
}
});
// Observe immediately, though we trigger a manual resize check to establish baseline
resizeObserver.observe(container);
// Setup Render Loop
let animationId;
function animate() {
animationId = requestAnimationFrame(animate);
controls.update(); // necessary because of enableDamping = true
renderer.render(scene, camera);
}
animate();
// 6. Provide control hints overlays
const hint = document.createElement('div');
hint.textContent = 'Drag to Rotate ยท Scroll to Zoom';
hint.style.position = 'absolute';
hint.style.bottom = '10px';
hint.style.left = '50%';
hint.style.transform = 'translateX(-50%)';
hint.style.color = 'rgba(255, 255, 255, 0.7)';
hint.style.textShadow = '1px 1px 2px rgba(0,0,0,0.8)';
hint.style.fontFamily = 'sans-serif';
hint.style.fontSize = '12px';
hint.style.pointerEvents = 'none';
container.appendChild(hint);
// 7. Cleanup protocol (Detects if container is removed from DOM)
// The delay prevents immediate triggering during container manipulation in the parent
setTimeout(() => {
const mutationObserver = new MutationObserver(() => {
if (!document.body.contains(container)) {
cancelAnimationFrame(animationId);
mutationObserver.disconnect();
resizeObserver.disconnect();
renderer.dispose();
geometry.dispose();
material.dispose();
colorTexture.dispose();
displacementTexture.dispose();
}
});
mutationObserver.observe(document.body, { childList: true, subtree: true });
}, 1000);
return container;
}
Apply Changes