如何在three.js中设置图像背景?

时间:2017-08-01 16:32:53

标签: javascript css three.js

我正在尝试用three.js中的globe设置我的场景的图像背景,但不幸的是,当我这样做时,我的场景的主要对象也变成了黑色(背景颜色相同。

我使用的方法:

renderer = new THREE.WebGLRenderer({ antialias: false, alpha:true });

这使默认背景透明。然后我在CSS部分添加了图像背景。

我对场景的整个脚本如下所示:     

        var container, stats;
        var camera, scene, renderer;
        var group;
        var mouseX = 0, mouseY = 0;

        var windowHalfX = window.innerWidth / 2;
        var windowHalfY = window.innerHeight / 2;

        init();
        animate();


        function init() {

            container = document.getElementById( 'container' );

            camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 2000 );
            //closer
            camera.position.z = 500;

            scene = new THREE.Scene();

            group = new THREE.Group();
            scene.add( group );

            // earth

            var loader = new THREE.TextureLoader();
            loader.load( 'textures/mapnew1.jpg', function ( texture ) {

                var geometry = new THREE.SphereGeometry( 180, 32, 32 );

                var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
                var mesh = new THREE.Mesh( geometry, material );
                group.add( mesh );

            } );



            // shadow

            var canvas = document.createElement( 'canvas' );
            canvas.width = 128;
            canvas.height = 128;

            var context = canvas.getContext( '2d' );
            var gradient = context.createRadialGradient(
                canvas.width / 2,
                canvas.height / 2,
                0,
                canvas.width / 2,
                canvas.height / 2,
                canvas.width / 2
            );
            gradient.addColorStop( 0.1, '#000000' );
            gradient.addColorStop( 1, '#000000' );

            context.fillStyle = gradient;
            context.fillRect( 0, 0, canvas.width, canvas.height );

            var texture = new THREE.CanvasTexture( canvas );

            var geometry = new THREE.PlaneBufferGeometry( 300, 300, 3, 3 );
            var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );


            var mesh = new THREE.Mesh( geometry, material );
            mesh.position.y = - 200;
            mesh.rotation.x = - Math.PI / 2;
            group.add( mesh );


            renderer = new THREE.CanvasRenderer();
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer = new THREE.WebGLRenderer({ antialias: false, alpha:true });
            renderer.setSize( window.innerWidth, window.innerHeight );
            renderer.setClearColor(0x000000, 0);
            container.appendChild( renderer.domElement );

            stats = new Stats();
            container.appendChild( stats.dom );

            document.addEventListener( 'mousemove', onDocumentMouseMove, false );

            //

            window.addEventListener( 'resize', onWindowResize, false );

        }

        function onWindowResize() {

            windowHalfX = window.innerWidth / 2;
            windowHalfY = window.innerHeight / 2;

            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();

            renderer.setSize( window.innerWidth, window.innerHeight );

        }

        function onDocumentMouseMove( event ) {

            mouseX = ( event.clientX - windowHalfX );
            mouseY = ( event.clientY - windowHalfY );

        }

        //

        function animate() {

            requestAnimationFrame( animate );

            render();
            stats.update();

        }


        function render() {

            camera.position.x += ( mouseX - camera.position.x ) * 0.08;
            camera.position.y += ( - mouseY - camera.position.y ) * 0.08;
            camera.lookAt( scene.position );

            group.rotation.y -= 0.003;

            renderer.render( scene, camera );


        }


    </script>

这是我的CSS:

body {
  color: #ffffff;
  font-family:'Futura';
  font-size:20px;
  text-align: center;
  background-image: url(textures/starfield.png);
  background-color: black;
  margin: 0px;
  overflow: hidden;
}

您是否有任何想法如何解决它并使全球可见?

非常感谢!

3 个答案:

答案 0 :(得分:1)

关于背景图片,您要为alpha设置WebGLRenderer值,这是正确的。您没有发布CSS,但确保在container上设置背景图片,而不是在画布上。

另外,请注意这一行:

renderer.setClearColor(0x000000, 0);

您不需要设置清晰的颜色,因为您要清除透明度而不是颜色。这应解决背景图片问题。

关于全黑模型,您需要在场景中使用灯光。尝试将此添加到您的init方法:

var light = new THREE.PointLight(0xffffff, 1, Infinity);
camera.add(light);

这将在相机位置添加光源(并在相机移动时跟随相机)。

编辑以添加代码段

var container, stats;
var camera, scene, renderer;
var group;
var mouseX = 0,
  mouseY = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

init();
animate();


function init() {

  container = document.getElementById('container');

  camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 2000);
  //closer
  camera.position.z = 500;
  
  var light = new THREE.PointLight(0xffffff, 1, Infinity);
  camera.add(light);

  scene = new THREE.Scene();

  group = new THREE.Group();
  scene.add(group);

  // earth

  var loader = new THREE.TextureLoader();
  loader.crossOrigin = '';
  loader.load('https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Equirectangular_projection_SW.jpg/640px-Equirectangular_projection_SW.jpg', function(texture) {
    var geometry = new THREE.SphereGeometry(180, 32, 32);

    var material = new THREE.MeshBasicMaterial({
      map: texture,
      overdraw: 0.5
    });
    var mesh = new THREE.Mesh(geometry, material);
    group.add(mesh);

  });



  // shadow

  var canvas = document.createElement('canvas');
  canvas.width = 128;
  canvas.height = 128;

  var context = canvas.getContext('2d');
  var gradient = context.createRadialGradient(
    canvas.width / 2,
    canvas.height / 2,
    0,
    canvas.width / 2,
    canvas.height / 2,
    canvas.width / 2
  );
  gradient.addColorStop(0.1, '#000000');
  gradient.addColorStop(1, '#000000');

  context.fillStyle = gradient;
  context.fillRect(0, 0, canvas.width, canvas.height);

  var texture = new THREE.CanvasTexture(canvas);

  var geometry = new THREE.PlaneBufferGeometry(300, 300, 3, 3);
  var material = new THREE.MeshBasicMaterial({
    map: texture,
    overdraw: 0.5
  });


  var mesh = new THREE.Mesh(geometry, material);
  mesh.position.y = -200;
  mesh.rotation.x = -Math.PI / 2;
  group.add(mesh);


  renderer = new THREE.WebGLRenderer({
    antialias: false,
    alpha: true
  });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  //renderer.setClearColor(0x000000, 0);
  container.appendChild(renderer.domElement);

  stats = new Stats();
  container.appendChild(stats.dom);

  document.addEventListener('mousemove', onDocumentMouseMove, false);

  //

  window.addEventListener('resize', onWindowResize, false);

}

function onWindowResize() {

  windowHalfX = window.innerWidth / 2;
  windowHalfY = window.innerHeight / 2;

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);

}

function onDocumentMouseMove(event) {

  mouseX = (event.clientX - windowHalfX);
  mouseY = (event.clientY - windowHalfY);

}

//

function animate() {

  requestAnimationFrame(animate);

  render();
  stats.update();

}


function render() {

  camera.position.x += (mouseX - camera.position.x) * 0.08;
  camera.position.y += (-mouseY - camera.position.y) * 0.08;
  camera.lookAt(scene.position);

  group.rotation.y -= 0.003;

  renderer.render(scene, camera);


}
body {
  color: #ffffff;
  font-family: 'Futura';
  font-size: 20px;
  text-align: center;
  background-image: url(https://upload.wikimedia.org/wikipedia/commons/6/62/Starsinthesky.jpg);
  background-color: black;
  margin: 0px;
  overflow: hidden;
}
<script src="https://threejs.org/build/three.js"></script>
<script src="https://threejs.org/examples/js/renderers/Projector.js"></script>
<script src="https://threejs.org/examples/js/libs/stats.min.js"></script>
<div id="container"></div>

three.js r86

答案 1 :(得分:1)

有一段时间,有:

var texture = new THREE.TextureLoader().load( "textures/bg.jpg" );
scene.background = texture;

我使用three.js v 0.87

答案 2 :(得分:1)

有两种方法可以做到

1)使用TextureLoader加载图像并将其设置为背景。这将导致静态背景,看起来可能不太现实。

 var texture = new THREE.TextureLoader().load(
      "https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
    );
   scene.background = texture;

2)使用skybox为顶部,左侧,右侧底部,正面背面加载图像。然后将它们设置在立方体或球体几何内部

var urls = [
      "https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg",
      "https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg",
      "https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg",
      "https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg",
      "https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg",
      "https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg"
    ];

    var materialArray = [];
    for (var i = 0; i < 6; i++)
      materialArray.push(
        new THREE.MeshBasicMaterial({
          map: new THREE.TextureLoader().load(urls[i]),
          side: THREE.BackSide
        })
      );

    var skyGeometry = new THREE.SphereGeometry(400, 32, 32);
    var skyMaterial = new THREE.MeshFaceMaterial(materialArray);
    var skybox = new THREE.Mesh(skyGeometry, skyMaterial);
    scene.add(skybox);

这将使球体的背面具有图像纹理。只需将THREE.SphereGeometry替换为THREE.CubeGeometry,就可以模拟envMap。