Writing 3D Visual Code with LLMs: What to Delegate and What to Review
Frontend development has expanded into 3D visualization and immersive interfaces, bringing challenges like abstract graphics concepts and cross-browser inconsistencies. While Large Language Models (LLMs) can accelerate boilerplate generation, their output still requires rigorous testing and review. This article explores how to effectively use LLMs for 3D and frontend visual tasks, providing prompt templates and code examples for scene initialization, shader writing, physics animation, and responsive layout, along with a comprehensive review and testing checklist.
Frontend development has evolved from form submissions and static pages to 3D visualization, complex animations, and immersive interfaces. Developers often encounter three issues in such projects: abstract graphics concepts, the need to repeatedly adjust matrices and lighting parameters, and inconsistent visual results across different browsers and devices. While LLMs can shorten the time spent writing boilerplate code, the code they generate still needs to be run, tested, and reviewed. This article introduces approaches categorized by task type, providing prompt templates, examples, and runtime environment specifications.
1. Challenges in 3D and Frontend Visual Development
When using WebGL, developers must simultaneously handle the scene graph, camera, lighting, materials, and the render loop. Even creating a simple lit rotating cube requires writing renderer initialization, size adaptation, and an animation loop. Wrapper libraries like Three.js lower the barrier to entry, but developers still need to understand coordinate systems, transform orders, and the basics of shaders.
Frontend animations carry a similar burden. CSS animations should prioritize using transform and opacity to avoid triggering layout reflows. Canvas requires manual per-frame drawing management. Dynamic SVG path generation requires familiarity with path instructions. When requirements change rapidly, hand-writing this code slows down delivery.
2. Prompts and Examples for Four Task Types
LLMs excel at converting natural language requirements into structured code. The following four tasks are suitable for having the model generate an initial draft, followed by developer execution and adjustments.
Runtime Environment Note: The examples use Three.js r160, loaded via an importmap from a CDN, and require an internet connection. The page must be opened through a local server or a live URL, such as executing npx serve . or python -m http.server. Directly double-clicking the HTML file may fail due to module loading restrictions. The browser must support WebGL2; mainstream versions of Chrome, Edge, Firefox, and Safari all meet this requirement.
2.1 Scene Initialization: How to Write the Prompt
The prompt needs to clearly specify the role, library name and version, scene elements, and interaction requirements. The following prompt can yield well-structured initialization code:
Role: Senior Frontend Graphics DeveloperTech Stack: Three.js r160, ES Modules, no build toolsRequirements: Create a perspective camera, a renderer, and a scene with ambient light and a directional light. Place a blue cube in the center that rotates uniformly around the Y-axis and changes to a random color when clicked.Constraints: The renderer size should adapt to the window; use setAnimationLoop; animation speed should be calculated based on frame intervals, independent of frame rate.Output: A complete HTML file that can be opened directly in a browser.
Below is the complete file, organized and manually proofread according to the prompt. Save it as scene.html and open it via a local server to see the effect.
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Rotating Cube</title><style>html, body { margin: 0; height: 100%; overflow: hidden; }canvas { display: block; }</style><script type="importmap">{"imports": {"three": "https://unpkg.com/three@0.160.0/build/three.module.js"}}</script></head><body><script type="module">import * as THREE from 'three';const scene = new THREE.Scene();scene.background = new THREE.Color(0x202020);const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100);camera.position.z = 4;const renderer = new THREE.WebGLRenderer({ antialias: true });renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));renderer.setSize(window.innerWidth, window.innerHeight);document.body.appendChild(renderer.domElement);const ambient = new THREE.AmbientLight(0xffffff, 0.4);const sun = new THREE.DirectionalLight(0xffffff, 1.0);sun.position.set(3, 5, 4);scene.add(ambient, sun);const material = new THREE.MeshStandardMaterial({ color: 0x1e6fff });const cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), material);scene.add(cube);const ROTATE_SPEED = Math.PI / 2; // Radians per secondconst clock = new THREE.Clock();renderer.domElement.addEventListener('click', () => {material.color.setHex(Math.floor(Math.random() * 0xffffff));});window.addEventListener('resize', () => {camera.aspect = window.innerWidth / window.innerHeight;camera.updateProjectionMatrix();renderer.setSize(window.innerWidth, window.innerHeight);});renderer.setAnimationLoop(() => {const dt = clock.getDelta();cube.rotation.y += ROTATE_SPEED * dt;renderer.render(scene, camera);});</script></body></html>
The code returned by the model still needs to be run locally. Common issues include inconsistent variable names, legacy API remnants, and version mismatches between the importmap and the code.
2.2 Shader Writing: Generating a Fire Effect
GLSL code is logic-dense and costly to debug. The prompt should specify the coordinate range, input variables, output color, and time variables.
Role: Senior WebGL Shader DeveloperTech Stack: Three.js r160, ShaderMaterial, gl_FragColor syntax, no build toolsRequirements: Draw a fire effect on a plane mesh. The vertical color should transition from bright yellow at the bottom to dark red at the top. Edges should be disturbed by noise and flow upward over time.Constraints: All animations must be driven only by the uniform uTime; noise frequency should be exposed as named parameters for easy adjustment; do not use features requiring extension support.Output: vertexShader, fragmentShader, and JavaScript mounting code, and explain the meaning of each uniform.
The following script replaces the content of the <script type="module"> from the first section’s HTML, with the rest remaining unchanged. Replace the material related code with the shader material to get a fire plane.
import * as THREE from 'three';const scene = new THREE.Scene();scene.background = new THREE.Color(0x101010);const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 100);camera.position.z = 5;const renderer = new THREE.WebGLRenderer({ antialias: true });renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));renderer.setSize(window.innerWidth, window.innerHeight);document.body.appendChild(renderer.domElement);const vertexShader = `varying vec2 vUv;void main() {vUv = uv;gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);}`;const fragmentShader = `uniform float uTime;varying vec2 vUv;float hash(vec2 p) {return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);}float noise(vec2 p) {vec2 i = floor(p);vec2 f = fract(p);vec2 u = f * f * (3.0 - 2.0 * f);float a = hash(i);float b = hash(i + vec2(1.0, 0.0));float c = hash(i + vec2(0.0, 1.0));float d = hash(i + vec2(1.0, 1.0));return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);}void main() {vec2 p = vUv * vec2(4.0, 6.0);p.y -= uTime * 1.5;float n = noise(p) * 0.6 + noise(p * 2.0) * 0.4;float heat = (1.0 - vUv.y) * 0.8 + n * 0.5;vec3 color = mix(vec3(0.1, 0.0, 0.0), vec3(1.0, 0.6, 0.1), smoothstep(0.2, 0.9, heat));float alpha = smoothstep(0.0, 0.3, heat);gl_FragColor = vec4(color, alpha);}`;const fireMaterial = new THREE.ShaderMaterial({uniforms: {uTime: { value: 0 }},vertexShader,fragmentShader,transparent: true});const plane = new THREE.Mesh(new THREE.PlaneGeometry(3, 4), fireMaterial);scene.add(plane);const clock = new THREE.Clock();window.addEventListener('resize', () => {camera.aspect = window.innerWidth / window.innerHeight;camera.updateProjectionMatrix();renderer.setSize(window.innerWidth, window.innerHeight);});renderer.setAnimationLoop(() => {fireMaterial.uniforms.uTime.value = clock.getElapsedTime();renderer.render(scene, camera);});
There are a few key points in this code. vUv is passed from the vertex shader to the fragment shader to determine the vertical gradient. uTime must be updated every frame, or the fire will remain static. transparent: true allows alpha to take effect. The sin hash in the noise lacks precision on some mobile GPUs; if banding occurs, check the precision or switch to a different hash function.
2.3 Physics Animation: Writing a Bouncing Ball
There are two common errors in physics animation: directly applying the time step to integration, which causes the ball to penetrate the ground after switching browser tabs; and calling clock.getDelta() multiple times in the same frame, leading to disordered time increments. The prompt should include these two points as constraints.
Role: Senior Frontend Physics Animation EngineerTech Stack: Three.js r160, hand-written Euler integration, no physics engineRequirements: A ball falls from a height, bounces off the ground according to a coefficient of restitution, and eventually comes to a stop.Constraints: The time step is calculated based on frame intervals and has a maximum cap; gravity, restitution coefficient, and ground height are named constants; the time increment is read only once per frame.Output: A code snippet that can be integrated into an existing scene, along with notes on numerical stability.
The following code follows the scene file from the first section. Replace the entire renderer.setAnimationLoop from the first section with the version below, and add the ball’s declaration before it.
const ball = new THREE.Mesh(new THREE.SphereGeometry(0.2, 32, 16),new THREE.MeshStandardMaterial({ color: 0xffcc00 }));ball.position.set(1.5, 2, 0);scene.add(ball);const GRAVITY = -9.8; // Meters per second squaredconst RESTITUTION = 0.7; // Velocity retention ratio after bounceconst GROUND_Y = -1.5;const BALL_RADIUS = 0.2;const MAX_DT = 1 / 30; // Cap single frame step to prevent ground penetration when switching tabsconst velocity = new THREE.Vector3();let resting = false;renderer.setAnimationLoop(() => {const dt = Math.min(clock.getDelta(), MAX_DT);cube.rotation.y += ROTATE_SPEED * dt;if (!resting) {velocity.y += GRAVITY * dt;ball.position.addScaledVector(velocity, dt);const floor = GROUND_Y + BALL_RADIUS;if (ball.position.y <= floor) {ball.position.y = floor;velocity.y = -velocity.y * RESTITUTION;if (velocity.y < 0.05) {velocity.y = 0;resting = true;}}}renderer.render(scene, camera);});
For numerical stability, three points need attention. First, the time step cap must exist; otherwise, a large step will make the ball skip the ground. Second, Euler integration is sufficient for this example, but if many colliders are added, sub-stepping or a mature physics engine should be used. Third, the stop condition is handled using a velocity threshold; if the threshold is too small, micro-jitter will occur, and if too large, the ball will stop prematurely.
2.4 Responsive Layout: Adapting Canvas to Container
The Canvas size should be determined by its container, not bound directly to the window. Otherwise, the size will be misaligned when the page has sidebars or multiple canvases. The prompt can be written like this:
Role: Senior Frontend EngineerTech Stack: Vanilla HTML/CSS, CSS Grid, ResizeObserver, Three.js r160Requirements: The page contains a title and a 3D canvas. Desktop has two columns, mobile has one column, and the canvas maintains a 16:9 ratio.Constraints: Font sizes use clamp(); canvas size is determined by the container, not window; do not use fixed pixel widths.Output: HTML structure, CSS, and the script binding ResizeObserver.
The following structure is the same as the HTML file in the first section, replacing only the <body> and <style>, and using the script below.
<style>body { margin: 0; font-family: system-ui, sans-serif; }.layout {display: grid;grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr));gap: clamp(12px, 2vw, 24px);padding: clamp(16px, 4vw, 40px);}h1 { font-size: clamp(1.25rem, 2.5vw + 0.5rem, 2.5rem); }.stage { aspect-ratio: 16 / 9; min-height: 220px; }.stage canvas { display: block; width: 100%; height: 100%; }</style></head><body><div class="layout"><section><h1>Rotating Cube</h1><p>Adjust the browser width to observe the canvas ratio remaining unchanged.</p></section><div class="stage" id="stage"></div></div><script type="module">import * as THREE from 'three';const stage = document.getElementById('stage');const renderer = new THREE.WebGLRenderer({ antialias: true });renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));stage.appendChild(renderer.domElement);const scene = new THREE.Scene();scene.add(new THREE.AmbientLight(0xffffff, 0.4));const sun = new THREE.DirectionalLight(0xffffff, 1.0);sun.position.set(3, 5, 4);scene.add(sun);const camera = new THREE.PerspectiveCamera(60, 16 / 9, 0.1, 100);camera.position.z = 4;const cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1),new THREE.MeshStandardMaterial({ color: 0x1e6fff }));scene.add(cube);const ro = new ResizeObserver(([entry]) => {const { width, height } = entry.contentRect;renderer.setSize(width, height, false);camera.aspect = width / height;camera.updateProjectionMatrix();});ro.observe(stage);renderer.setAnimationLoop(() => {cube.rotation.y += 0.01;renderer.render(scene, camera);});</script>
The third parameter of setSize is set to false, meaning it does not write inline styles for the canvas, leaving size control to CSS. If this parameter is omitted, the canvas will carry a fixed pixel size, and the responsive layout will immediately fail.
3. Code Review, Testing, and Cost Evaluation
Review Checklist
Code generated by the model needs to be checked item by item:
- Version Consistency: Does the Three.js version in the importmap, the APIs used in the code, and the documentation correspond? The legacy
THREE.Geometrywas removed in r125, but models often mix in old syntax. - Dependency Sources: Are the CDN addresses pinned to specific version numbers? Are there any third-party libraries from unknown sources?
- Variables and State: Are all variables declared? Is the state in the animation correctly updated in every frame?
- Shaders: Are there divisions by zero, unupdated uniforms, or mobile precision issues?
- Edge Case Inputs: Is there handling for when the window size is zero, the canvas is hidden, or WebGL is unavailable?
- Security: Do not write model output directly into
innerHTML, do not useeval, and do not hardcode API keys in frontend code.
Testing Steps
- Local Execution: Open via a local server and check the console for errors or warnings.
- Multi-Browser Verification: Open in at least Chrome, Firefox, and Safari, and compare whether colors and lighting are consistent.
- Mobile Device Verification: Test on actual devices to verify performance and rendering.
