| 3 | import "./CubeScene.css"; |
| 4 | |
| 5 | class CubeScene extends Component { |
| 6 | constructor(props) { |
| 7 | super(props); |
| 8 | this.firstSideLength = props.sideLength; |
| 9 | } |
| 10 | |
| 11 | wrapEl = null; |
| 12 | |
| 13 | camera = null; |
| 14 | scene = null; |
| 15 | renderer = null; |
| 16 | mesh = null; |
| 17 | |
| 18 | componentDidMount() { |
| 19 | if (this.isWebGlSupport) { |
| 20 | this.init(this.props.sideLength); |
| 21 | window.addEventListener("resize", this.onWindowResize, false); |
| 22 | this.animate(); |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | isWebGlSupport = () => { |
| 27 | const canvas = document.createElement("canvas"); |
| 28 | const gl = |
| 29 | canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); |
| 30 | return gl && gl instanceof WebGLRenderingContext; |
| 31 | }; |
| 32 | |
| 33 | init(length) { |
| 34 | const width = this.wrapEl.offsetWidth; |
| 35 | const height = this.wrapEl.offsetHeight; |
| 36 | |
| 37 | this.camera = new THREE.PerspectiveCamera(70, width / height, 1, 1000); |
| 38 | this.camera.position.z = 400; |
| 39 | |
| 40 | this.scene = new THREE.Scene(); |
| 41 | |
| 42 | const geometry = new THREE.BoxBufferGeometry(length, length, length); |
| 43 | const material = new THREE.MeshNormalMaterial(); |
| 44 | this.mesh = new THREE.Mesh(geometry, material); |
| 45 | |
| 46 | this.scene.add(this.mesh); |
| 47 | |
| 48 | this.renderer = new THREE.WebGLRenderer({ antialias: true }); |
| 49 | this.renderer.setPixelRatio(window.devicePixelRatio); |
| 50 | this.renderer.setSize(width, height); |
| 51 | |
| 52 | this.wrapEl.appendChild(this.renderer.domElement); |
| 53 | } |
| 54 | |
| 55 | onWindowResize = () => { |
| 56 | const width = this.wrapEl.offsetWidth; |
| 57 | const height = this.wrapEl.offsetHeight; |
| 58 | |
| 59 | this.camera.aspect = width / height; |
| 60 | this.camera.updateProjectionMatrix(); |
| 61 | this.renderer.setSize(width, height); |
| 62 | }; |