立方體貼圖能夠是6個獨立的圖片,爲了減小HTTP請求也能夠把6張圖片合併在一塊兒作成一個圖片,原理是在建立的canvas上把圖片按順序截取顯示在畫布上,並並把顯示圖片的畫布賦予紋理對象的image屬性,並設置材質對象的needsUpdate = true,而後把生成的紋理映射成材質對象,經過形狀與材質生成box。html
<!DOCTYPE html> <html lang="en"> <head> <title>three.js webgl - panorama</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <style> html, body { margin: 0; padding: 0; overflow: hidden; } #container { width: 1500px; height: 800px; background: #000; } </style> </head> <body> <div id="container"></div> <script src="../../build/three.js"></script> <script src="../js/controls/OrbitControls.js"></script> <script> var camera, controls; var renderer; var scene; var width, height; init(); animate(); function init(){ var container = document.getElementById("container"); width = container.clientWidth; height = container.clientHeight; renderer = new THREE.WebGLRenderer(); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(width,height); container.appendChild(renderer.domElement); scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(90,width/height,0.1,100); camera.position.z = 0.01; controls = new THREE.OrbitControls(camera, renderer.domElement); var textures = getTexturesFromAtlasFile( "../textures/cube/sun_temple_stripe.jpg", 6 ); var materials = []; for(var i=0;i<6;i++){ materials.push(new THREE.MeshBasicMaterial({map:textures[i]})) } var skyBox = new THREE.Mesh( new THREE.BoxBufferGeometry( 1, 1, 1 ), materials ); skyBox.geometry.scale(1,1,-1); scene.add(skyBox); window.addEventListener("resize",onWindowResize,false) } function getTexturesFromAtlasFile( atlasImgUrl, titlesNum ) { var textures = []; for(var i =0;i<titlesNum;i++){ textures[i] = new THREE.Texture() } var imageObj = new Image(); imageObj.onload = function(){ var canvas, context; var imgWidth = imageObj.height; for(var i=0;i<6;i++){ canvas = document.createElement("canvas"); context = canvas.getContext("2d"); canvas.height = imgWidth; canvas.width = imgWidth; context.drawImage(imageObj,imgWidth*i,0,imgWidth,imgWidth,0,0,imgWidth,imgWidth); textures[i].image = canvas; textures[i].needsUpdate = true; } } imageObj.src = atlasImgUrl; return textures; } function onWindowResize() { camera.aspect = width / height; camera.updateProjectionMatrix(); renderer.setSize(width, height); } function animate() { requestAnimationFrame(animate); controls.update(); renderer.render(scene, camera) } </script> </body> </html>