CSS2DRenderer.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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.setSize = function ( width, height ) {
  28. _width = width;
  29. _height = height;
  30. _widthHalf = _width / 2;
  31. _heightHalf = _height / 2;
  32. domElement.style.width = width + 'px';
  33. domElement.style.height = height + 'px';
  34. };
  35. var renderObject = function ( object, camera ) {
  36. if ( object instanceof THREE.CSS2DObject ) {
  37. vector.setFromMatrixPosition( object.matrixWorld );
  38. vector.applyMatrix4( viewProjectionMatrix );
  39. var element = object.element;
  40. var style = 'translate(-50%,-50%) translate(' + ( vector.x * _widthHalf + _widthHalf ) + 'px,' + ( - vector.y * _heightHalf + _heightHalf ) + 'px)';
  41. element.style.WebkitTransform = style;
  42. element.style.MozTransform = style;
  43. element.style.oTransform = style;
  44. element.style.transform = style;
  45. if ( element.parentNode !== domElement ) {
  46. domElement.appendChild( element );
  47. }
  48. }
  49. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  50. renderObject( object.children[ i ], camera );
  51. }
  52. };
  53. this.render = function ( scene, camera ) {
  54. scene.updateMatrixWorld();
  55. if ( camera.parent === null ) camera.updateMatrixWorld();
  56. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  57. viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  58. viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, viewMatrix );
  59. renderObject( scene, camera );
  60. };
  61. };