【发布时间】:2021-04-02 04:37:18
【问题描述】:
我正在使用服务器来生成图表的 base64 字符串表示。然后通过使用 POST 请求获取数据来加载它以响应组件。数据加载到反应状态,但场景在纹理加载之前渲染。我已经阅读了 Is there a way to wait for THREE.TextureLoader.load() to finish? ,我是否也应该使用 promise ?我想使用反应状态进行交流,因为最终的交流会比下面的例子更复杂。
const Comp= () => {
const [state, setState] = useState(null)
// basic three.js scene setting
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(28, 1, 1, 1000);
camera.position.set(75, 25, 50);
camera.lookAt(scene.position);
scene.add(camera);
camera.add(new THREE.PointLight(0xffffff, 1, Infinity));
var cubeGeo = new THREE.BoxBufferGeometry(3,3, 0.0001);
// fetching data
const getFile = (event) => {
fetch('http://127.0.0.1:5000/getFile',
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST'
})
.then(response => response.json())
.then(response => setState(response.state))
}
// fetch data when loading
useEffect(
() => getFile(), []
)
// use effect when change of state happens
// (it depends on [state])
useEffect(
() => {
// state contains image data as string representation of base64
var texture = new THREE.TextureLoader().load("data:image/jpeg;base64," + state);
var mat = new THREE.MeshBasicMaterial({ map: texture });
var cubes = []
const n = 100;
const V = 111;
// rest is irrelevant
for (var i = 0; i < n; i++) {
var mesh = new THREE.Mesh(cubeGeo, mat);
cubes[i] = mesh
var x = V * (Math.random() - .5);
var y = V * (Math.random() - .5);
var z = V * (Math.random() - .5);
var r = Math.sqrt(x ** 2 + y ** 2 + z ** 2) / 20
x /= r
y /= r
z /= r
// console.log(r, x,y,z)
cubes[i].position.x = x;
cubes[i].position.y = y;
cubes[i].position.z = z;
scene.add(cubes[i]);
}
}, [state])
return (
<p ref={() => animate()} />
)
}
export default Comp;
【问题讨论】:
标签: javascript reactjs three.js render-to-texture