Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html>
	<head>
		<title>ThreeJS Tips: 20-22</title>
	</head>
	<body>
    <div class="msg"><p>The maps on the apples are all square. Left to right the sizes are 128, 256, 512, 1024, 2048</p></div>
    <h2><a href="https://niklever.com/courses" class="overlay" target="_blank">niklever.com/courses</a></h2>
		<script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>

<script type="importmap">
  {
    "imports": {
      "three": "https://unpkg.com/three@0.142.0/build/three.module.js"
    }
  }
</script>

	</body>
</html>
              
            
!

CSS

              
                body { margin: 0; }
canvas { width: 100%; height: 100%; position: absolute; top: 0 }
.overlay { font-family: Arial; z-index: 1001; position: absolute; bottom: 0; margin: 20px 20px; text-decoration: none; color: #fff}
.msg { font-family: Arial; z-index: 1002; position: absolute; width:100%; text-align: center; top: 50px; margin: auto; color: #fff}
              
            
!

JS

              
                import * as THREE from 'three';
import {OrbitControls} from 'https://unpkg.com/three@0.142.0/examples/jsm/controls/OrbitControls.js';
import {GLTFLoader} from 'https://unpkg.com/three@0.142.0/examples/jsm/loaders/GLTFLoader.js';
import {DRACOLoader} from 'https://unpkg.com/three@0.142.0/examples/jsm/loaders/DRACOLoader.js';
import {RGBELoader} from 'https://unpkg.com/three@0.142.0/examples/jsm/loaders/RGBELoader.js';
import {LoadingBar} from 'https://niksgames.com/threejs-games-course/libs/LoadingBar.js';
import GUI from 'https://unpkg.com/three@0.142.0/examples/jsm/libs/lil-gui.module.min.js';

//Tip 20: Texture POT
//Tip 21: Smallest texture
//Tip 22: Disable stencil buffer - line 21

let camera, scene, renderer, envmap;
let light, clock, loadingBar;

init();

function init() {

  
  renderer = new THREE.WebGLRenderer({antialias: true, stencil: false});
  renderer.setPixelRatio( Math.min(2, window.devicePixelRatio ));
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );
  renderer.outputEncoding = THREE.sRGBEncoding;
  renderer.physicallyCorrectLights = true;

  //
  clock = new THREE.Clock();
  
  camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 50 );
  camera.position.set( 0, 0, 0.7 );
  
  const col = 0x201510;
	scene = new THREE.Scene();
	scene.background = new THREE.Color( col );
	
  const ambient = new THREE.HemisphereLight(0xffffff, 0xbbbbff, 1);
		scene.add(ambient);

  light = new THREE.DirectionalLight( );
  light.position.set( 4, 20, 20);
  scene.add( light );

  if (!('ontouchstart' in window)) window.addEventListener( 'resize', onWindowResize, false );
  
  const controls = new OrbitControls( camera, renderer.domElement );
  controls.target.y = 0.05;
  controls.update()
  
  controls.addEventListener( 'change', () => {
    renderer.render( scene, camera );
  })
  
  setEnvironment();
  loadModel();
  
}

function setAutoUpdate(value){
  factory.traverse( child => {
    if (child.isMesh && !child.name.includes('fan')){
      child.matrixAutoUpdate = value;
    }
  })
}

function setEnvironment(){
        const loader = new RGBELoader();
        const pmremGenerator = new THREE.PMREMGenerator( renderer );
        pmremGenerator.compileEquirectangularShader();
        
        loader.load( 'https://niksgames.com/courses/model-viewer/assets/hdr/venice_sunset_1k.hdr', ( texture ) => {
          envmap = pmremGenerator.fromEquirectangular( texture ).texture;
          pmremGenerator.dispose();

          scene.environment = envmap;

        }, undefined, (err)=>{
            console.error( 'An error occurred setting the environment');
          console.error(err);
        } );
    }

function loadModel(){
  const loader = new GLTFLoader( ).setPath('https://niksgames.com/courses/threejs-cookbook/assets/');
  const dracoLoader = new DRACOLoader();
  dracoLoader.setDecoderPath( 'https://unpkg.com/three@0.142.0/examples/js/libs/draco/' );
  loader.setDRACOLoader( dracoLoader );
        
  loadingBar = new LoadingBar();
  loadingBar.visible = true;
		
		// Load a glTF resource
		loader.load(
			// resource URL
			'apple.glb',
			// called when the resource is loaded
			gltf => {

        const apple = gltf.scene.children[0];
				scene.add( apple );
        
        let xPos = -0.3;
        const inc = 0.15;
        let loaded = 0;
        
        for(let i=0; i<4; i++){
          const apple1 = apple.clone();
          const texSize = Math.pow(2, i+7);
          const name = `apple_${texSize}.jpg`;
          const texLoader = new THREE.TextureLoader();
          texLoader.setPath('https://niksgames.com/courses/threejs-cookbook/assets/');
          apple1.material = apple.material.clone();
          texLoader.load(name, (tex) => {
            tex.encoding = THREE.sRGBEncoding;
            tex.flipY = false;
            apple1.material.map = tex;
            loaded++;
            if (loaded==4) renderer.render(scene, camera);
          })
          
          apple1.position.x = xPos;
          scene.add(apple1);
          xPos += inc;
        }
        
        apple.position.x = xPos;
        
				loadingBar.visible = false;
        renderer.render( scene, camera );
			},
			// called while loading is progressing
			xhr => {

				loadingBar.update('environment', xhr.loaded, xhr.total);
				
			},
			// called when loading has errors
			err => {

				console.error( err );

			}
		);
    }

function onWindowResize() {

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

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

function render() {

  requestAnimationFrame( render );
  
  renderer.render(scene, camera);

}
              
            
!
999px

Console