如何使用Three.js从JSON文件读取数据并绘制3D图表
Got it, let's walk through this step by step—loading JSON data and turning it into a 3D chart with Three.js is straightforward once you break down the workflow. Here's how to do it:
1. Prepare Your JSON Data Structure
First, make sure your JSON file has a clear, consistent structure that maps to the 3D chart you want to build. For example, if you're making a scatter plot or bar chart, each entry should include position data (x/y/z) plus any visual properties like size or color.
Example data.json file:
{ "chartData": [ {"x": 1, "y": 6, "z": 2, "size": 0.6, "color": "#e74c3c"}, {"x": 2, "y": 3, "z": 4, "size": 0.8, "color": "#2ecc71"}, {"x": 3, "y": 8, "z": 1, "size": 0.5, "color": "#3498db"}, {"x": 4, "y": 4, "z": 3, "size": 0.7, "color": "#f39c12"} ] }
2. Load the JSON File
You have two reliable options to load your JSON data: using native browser fetch (modern and clean) or Three.js's built-in FileLoader (great if you want progress callbacks).
Option A: Using Fetch (Modern Approach)
// Async function to load and parse JSON async function loadChartData() { try { const response = await fetch('./data.json'); const jsonData = await response.json(); // Pass the parsed data to your chart creation function render3DChart(jsonData.chartData); } catch (error) { console.error('Failed to load data:', error); } } // Call the loader function loadChartData();
Option B: Using Three.js FileLoader
const loader = new THREE.FileLoader(); loader.load( './data.json', // On success: parse JSON and render function (rawData) { const jsonData = JSON.parse(rawData); render3DChart(jsonData.chartData); }, // On progress: track loading status function (xhr) { console.log(`${(xhr.loaded / xhr.total * 100).toFixed(0)}% loaded`); }, // On error: log issues function (error) { console.error('Error loading JSON:', error); } );
3. Render the 3D Chart from Data
Now that you have the parsed data, you can create 3D objects (like spheres for scatter plots, boxes for bar charts) and add them to your Three.js scene.
First, make sure you have your basic Three.js scene set up (you probably already have this, but just in case):
// Basic scene setup const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); camera.position.z = 15; // Adjust based on your data scale // Animation loop to keep the scene rendering function animate() { requestAnimationFrame(animate); // Optional: add subtle rotation to make the chart easier to view scene.rotation.y += 0.005; renderer.render(scene, camera); } animate();
Example 1: Scatter Plot
function render3DChart(dataPoints) { dataPoints.forEach(point => { // Create a sphere for each data point const geometry = new THREE.SphereGeometry(point.size, 16, 16); const material = new THREE.MeshBasicMaterial({ color: point.color }); const sphere = new THREE.Mesh(geometry, material); // Position the sphere using JSON data sphere.position.set(point.x, point.y, point.z); // Add to the scene scene.add(sphere); }); }
Example 2: Bar Chart
For bar charts, use BoxGeometry and adjust positions so bars sit on the "ground" (y=0):
function render3DChart(dataPoints) { // Add a directional light for better material visibility (if using MeshStandardMaterial) const light = new THREE.DirectionalLight(0xffffff, 1); light.position.set(5, 10, 7.5); scene.add(light); dataPoints.forEach(point => { // Bar dimensions: fixed width/depth, height from JSON y-value const geometry = new THREE.BoxGeometry(0.9, point.y, 0.9); const material = new THREE.MeshStandardMaterial({ color: point.color }); const bar = new THREE.Mesh(geometry, material); // Position bar so its bottom edge is at y=0 bar.position.set(point.x, point.y / 2, point.z); scene.add(bar); }); }
Key Notes to Remember
- File Paths: Ensure your JSON file is in the correct relative path from your HTML/JS file. If you're testing locally, use a local development server (like VS Code's Live Server extension) to avoid CORS errors.
- Data Consistency: Double-check that your JSON field names match what you're using in your code (e.g., if your JSON uses
heightinstead ofy, updatepoint.ytopoint.height). - Chart Types: Adjust the geometry based on your chart needs—use
THREE.Linefor line charts,THREE.CylinderGeometryfor column charts, etc.
内容的提问来源于stack exchange,提问作者vaidehi dhawale

