Doodle3D-Core/src/components/DoodlePreview.js

75 lines
1.9 KiB
JavaScript
Raw Normal View History

2017-10-24 12:33:14 +02:00
import * as THREE from 'three';
import 'three/examples/js/controls/EditorControls';
import React from 'react';
import PropTypes from 'proptypes';
import JSONToSketchData from '../shape/JSONToSketchData.js';
import createSceneData from '../d3/createSceneData.js';
import createScene from '../d3/createScene.js';
class DoodlePreview extends React.Component {
constructor() {
super();
this.state = {
scene: null
};
}
2017-11-02 22:53:47 +01:00
async componentDidMount() {
let { docData, sketchData } = this.props;
2017-10-24 12:33:14 +02:00
2017-11-02 22:53:47 +01:00
if (docData) sketchData = await JSONToSketchData(this.props.docData);
2017-10-24 12:33:14 +02:00
2017-11-02 22:53:47 +01:00
const { canvas } = this.refs;
const { width, height, pixelRatio } = this.props
2017-10-24 12:33:14 +02:00
2017-11-02 22:53:47 +01:00
const sceneData = createSceneData(sketchData);
const scene = createScene(sceneData, canvas);
this.setState({ scene });
scene.setSize(width, height, pixelRatio);
scene.render();
2017-10-24 12:33:14 +02:00
2017-11-02 22:53:47 +01:00
this.editorControls = new THREE.EditorControls(scene.camera, canvas);
this.editorControls.addEventListener('change', () => scene.render());
2017-10-24 12:33:14 +02:00
}
2017-11-06 14:40:19 +01:00
componentWillUnmount() {
if (this.editorControls) this.editorControls.dispose();
}
2017-10-24 12:33:14 +02:00
componentDidUpdate(prevProps) {
const { scene } = this.state;
const { width, height } = this.props;
if (scene !== null && (prevProps.width !== width || prevProps.height !== height)) {
scene.setSize(width, height);
scene.render();
}
}
render() {
2017-11-08 14:46:31 +01:00
const { width, height, className } = this.props;
2017-10-24 12:46:16 +02:00
return (
2017-11-08 14:48:54 +01:00
<canvas width={width} height={height} className={className} ref="canvas" />
2017-10-24 12:46:16 +02:00
);
2017-10-24 12:33:14 +02:00
}
}
DoodlePreview.defaultProps = {
width: 720,
height: 480,
pixelRatio: 1
};
DoodlePreview.propTypes = {
2017-11-08 14:46:31 +01:00
className: PropTypes.string,
2017-10-24 12:33:14 +02:00
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
pixelRatio: PropTypes.number.isRequired,
sketchData: PropTypes.object, // TODO
docData: PropTypes.shape({
appVersion: PropTypes.string,
data: PropTypes.string
})
};
export default DoodlePreview;