three.js dev template - module
HTML
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://raw.githack.com/mrdoob/three.js/dev/build/three.module.js",
"three/addons/": "https://raw.githack.com/mrdoob/three.js/dev/examples/jsm/"
}
}
</script>
CSS
body {
margin: 0px;
}
JavaScript
// Three.js scene with view-dependent rim lighting
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
let mesh, renderer, scene, camera, controls;
init();
animate();
function init() {
// renderer
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);
// scene
scene = new THREE.Scene();
// camera
camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(0, 0, 120);
// controls
controls = new OrbitControls(camera, renderer.domElement);
// ambient light
scene.add(new THREE.AmbientLight(0x222222));
// directional light
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(20, 20, 0).normalize();
scene.add(light);
// geometry
const geometry = new THREE.SphereGeometry(10, 50, 50);
// material
const material = new THREE.MeshPhongMaterial({ color: 0x808080 });
// add view-dependent rim light
material.onBeforeCompile = (shader) => {
shader.vertexShader = shader.vertexShader.replace(
'#include <common>',
`
#include <common>
varying vec3 vNormalW;
varying vec3 vViewDir;
`
);
shader.vertexShader = shader.vertexShader.replace(
'#include <fog_vertex>',
`
#include <fog_vertex>
vec4 worldPos = modelMatrix * vec4(position, 1.0);
vNormalW = normalize(mat3(modelMatrix) * normal);
vViewDir = normalize(cameraPosition - worldPos.xyz);
`
);
shader.fragmentShader = shader.fragmentShader.replace(
'#include <common>',
`
#include...