CSS2DRenderer.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. THREE.CSS2DObject = function ( element ) {
  5. THREE.Object3D.call( this );
  6. this.element = element;
  7. this.element.style.position = 'absolute';
  8. this.addEventListener( 'removed', function ( event ) {
  9. if ( this.element.parentNode !== null ) {
  10. this.element.parentNode.removeChild( this.element );
  11. }
  12. } );
  13. };
  14. THREE.CSS2DObject.prototype = Object.create( THREE.Object3D.prototype );
  15. THREE.CSS2DObject.prototype.constructor = THREE.CSS2DObject;
  16. //
  17. THREE.CSS2DRenderer = function () {
  18. console.log( 'THREE.CSS2DRenderer', THREE.REVISION );
  19. var _width, _height;
  20. var _widthHalf, _heightHalf;
  21. var vector = new THREE.Vector3();
  22. var viewMatrix = new THREE.Matrix4();
  23. var viewProjectionMatrix = new THREE.Matrix4();
  24. var domElement = document.createElement( 'div' );
  25. domElement.style.overflow = 'hidden';
  26. this.domElement = domElement;
  27. this.getSize = function () {
  28. return {
  29. width: _width,
  30. height: _height
  31. };
  32. };
  33. this.setSize = function ( width, height ) {
  34. _width = width;
  35. _height = height;
  36. _widthHalf = _width / 2;
  37. _heightHalf = _height / 2;
  38. domElement.style.width = width + 'px';
  39. domElement.style.height = height + 'px';
  40. };
  41. var renderObject = function ( object, camera ) {
  42. if ( object instanceof THREE.CSS2DObject ) {
  43. vector.setFromMatrixPosition( object.matrixWorld );
  44. vector.applyMatrix4( viewProjectionMatrix );
  45. var element = object.element;
  46. var style = 'translate(-50%,-50%) translate(' + ( vector.x * _widthHalf + _widthHalf ) + 'px,' + ( - vector.y * _heightHalf + _heightHalf ) + 'px)';
  47. element.style.WebkitTransform = style;
  48. element.style.MozTransform = style;
  49. element.style.oTransform = style;
  50. element.style.transform = style;
  51. if ( element.parentNode !== domElement ) {
  52. domElement.appendChild( element );
  53. }
  54. }
  55. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  56. renderObject( object.children[ i ], camera );
  57. }
  58. };
  59. this.render = function ( scene, camera ) {
  60. scene.updateMatrixWorld();
  61. if ( camera.parent === null ) camera.updateMatrixWorld();
  62. viewMatrix.copy( camera.matrixWorldInverse );
  63. viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, viewMatrix );
  64. renderObject( scene, camera );
  65. };
  66. };