shigeki.takeguchi.log

アラフィフおじさんの技術日記

thee.jsってReact風(react-three-rendererで)に書くと簡潔に書けるのかもしれない。

Reactをいろいろ触って試しているとThree.jsのオブジェクトをReact風(ライク)のコンポーネントとして書けるよっていうのがあって試してみました。 結論からいうと元のThree.jsの記述よりも長くなってあまり簡潔には書けませんでした。。。 ただしThree.js単体での記述よりも構造的で理解しやすいかなと思います。

これが今回使用したreact-three-rendererです。そのGithubのURLになります。
react-three-renderer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import React, { Component } from 'react';
import React3 from 'react-three-renderer';
import * as THREE from 'three';
import ReactDOM from 'react-dom';

class Simple extends Component {

constructor(props, context) {
super(props, context);
this.cameraPosition = new THREE.Vector3(0, 0, 5);
this.state = {
cubeRotation: new THREE.Euler(),
};

this._onAnimate = () => {
this.setState({
cubeRotation: new THREE.Euler(
this.state.cubeRotation.x + 0.1,
this.state.cubeRotation.y + 0.1,
0
),
});
};
}

render() {
const width = window.innerWidth;
const height = window.innerHeight;
return (<React3 mainCamera="camera" width={width} height={height} onAnimate={this._onAnimate}>
<scene>
<perspectiveCamera name="camera" fov={75} aspect={width / height} near={0.1} far={1000} position={this.cameraPosition} />
<mesh rotation={this.state.cubeRotation}>
<boxGeometry width={1} height={1} depth={1} />
<meshBasicMaterial color={0x00ff00} />
</mesh>
</scene>
</React3>);
}
}

ReactDOM.render(<Simple/>, document.body);

サンプルになっている緑色の立方体がくるくる回転するコードがこんな感じです。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import {Scene, PerspectiveCamera, WebGLRenderer, BoxGeometry, MeshBasicMaterial, Mesh} from 'three';

const scene = new Scene();
const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

const renderer = new WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const geometry = new BoxGeometry(1, 1, 1);
const material = new MeshBasicMaterial({color: 0x00ff00});
const cube = new Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

function render(){
requestAnimationFrame(render);
cube.rotation.x += 0.1;
cube.rotation.y += 0.1;
renderer.render(scene, camera);
}

render();

こっちがThree.jsのみでの同じく緑色の立方体がくるくる回転するコードです。 たしかに短いのはThree.js単体での記述ですが雑然とした感じですよね。まあ好みの問題だとは思います。

ここのところワンカットで撮影した散歩動画をYouTubeで配信してます。商店街や飲み屋街から観光地、城跡、坂など好奇心のおもむくまま撮影してます。動画を気に入ったらYouTubeのチャンネルも観てもらえると嬉しいです。https://www.youtube.com/c/shigekitakeguchi