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://unpkg.com/three@0.153/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.153/examples/jsm/"
}
}
</script>
CSS
body {
margin: 0px;
}
JavaScript
// Simple three.js example
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(20, 20, 20);
// controls
controls = new OrbitControls(camera, renderer.domElement);
// geometry
let geometry = new THREE.BoxGeometry(10, 10, 10);
geometry = geometry.toNonIndexed();
const positionAttribute = geometry.getAttribute('position');
const color = new THREE.Color();
const colors = [];
for (let i = 0; i < positionAttribute.count; i += 6) {
color.setHex(Math.random() * 0xffffff);
// face one
colors.push(color.r, color.g, color.b);
colors.push(color.r, color.g, color.b);
colors.push(color.r, color.g, color.b);
// face two
colors.push(color.r, color.g, color.b);
colors.push(color.r, color.g, color.b);
colors.push(color.r, color.g, color.b);
}
const colorAttribute = new THREE.Float32BufferAttribute(colors, 3);
geometry.setAttribute('color', colorAttribute);
const material = new THREE.MeshBasicMaterial({
vertexColors: true
});
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
}
function animate() {
requestAnimationFrame(animate);
//controls.update();
renderer.render(scene, camera);
}