SHARE
TWEET

Untitled

a guest Jan 12th, 2017 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import THREE from 'three'
  2.  
  3. export default class Scene {
  4.   constructor($container) {
  5.     this._$container = $container
  6.  
  7.     const { offsetWidth: width, offsetHeight: height } = this._$container
  8.  
  9.     this._scene = this._getScene()
  10.     this._camera = this._getCamera(width, height)
  11.     this._renderer = this._getRenderer(width, height)
  12.  
  13.     this._handleResizeBound = this._handleResize.bind(this)
  14.     this._drawBound = this._draw.bind(this)
  15.  
  16.     this._$container.appendChild(this._renderer.domElement)
  17.  
  18.     this._frameId = null
  19.  
  20.     this._addListeners()
  21.  
  22.     this._draw()
  23.   }
  24.  
  25.   _getScene() {
  26.     return new THREE.Scene()
  27.   }
  28.  
  29.   _getCamera(width, height) {
  30.     const camera = new THREE.PerspectiveCamera(45, width / height, 1, 100)
  31.     camera.position.z = 5
  32.  
  33.     return camera
  34.   }
  35.  
  36.   _getRenderer(width, height) {
  37.     const renderer = new THREE.WebGLRenderer({
  38.       alpha: true,
  39.       antialias: false
  40.     })
  41.  
  42.     renderer.setSize(width, height)
  43.     renderer.setClearColor(0x000000, 0)
  44.  
  45.     return renderer
  46.   }
  47.  
  48.   _addListeners() {
  49.     window.addEventListener('resize', this._handleResizeBound)
  50.   }
  51.  
  52.   _removeListeners() {
  53.     window.removeEventListener('resize', this._handleResizeBound)
  54.   }
  55.  
  56.   _handleResize() {
  57.     const { offsetWidth: width, offsetHeight: height } = this._$container
  58.  
  59.     this._camera.aspect = width / height
  60.     this._camera.updateProjectionMatrix()
  61.     this._renderer.setSize(width, height)
  62.   }
  63.  
  64.   _draw() {
  65.     this._frameId = requestAnimationFrame(this._drawBound)
  66.     this._renderer.render(this._scene, this._camera)
  67.   }
  68.  
  69.   add(...children) {
  70.     for(let i = 0; i < children.length; ++i) {
  71.       this._scene.add(children[i])
  72.     }
  73.   }
  74.  
  75.   remove(...children) {
  76.     for(let i = 0; i < children.length; ++i) {
  77.       this._scene.remove(children[i])
  78.     }
  79.   }
  80.  
  81.   dispose() {
  82.     this._removeListeners()
  83.     cancelAnimationFrame(this._frameId)
  84.   }
  85. }
RAW Paste Data
Top