three.js dev template - module
CSS
body {
margin: 0;
}
canvas {
display: block;
}
JavaScript
import * as THREE from "https://threejs.org/build/three.module.js";
import { OrbitControls } from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/examples/jsm/controls/OrbitControls.js';
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 5, 0);
camera.position.set(0, 5, 15);
controls.update();
const cubeSize = 4;
const cubeGeo = new THREE.BoxBufferGeometry(cubeSize, cubeSize, cubeSize);
const cubeMat = new THREE.MeshPhongMaterial({ color: '#8AC' });
const cube = new THREE.Mesh(cubeGeo, cubeMat);
cube.position.set(cubeSize + 1, cubeSize / 2, 0);
scene.add(cube);
const gizmos = [];
gizmos.push(cube);
const sphereRadius = 3;
const sphereWidthDivisions = 32;
const sphereHeightDivisions = 16;
const sphereGeo = new THREE.SphereBufferGeometry(sphereRadius, sphereWidthDivisions, sphereHeightDivisions);
const sphereMat = new THREE.MeshPhongMaterial({ color: '#CA8' });
const sphere = new THREE.Mesh(sphereGeo, sphereMat);
sphere.position.set(-sphereRadius - 1, sphereRadius + 2, 0);
scene.add(sphere);
const objects = [];
objects.push(sphere);
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.setScalar(1);
scene.add(light);
scene.add(new THREE.AmbientLight(0xffffff, 0.5));
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
function onMouseMove(event) {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(objects, true);
var invalidIntersects = raycaster.intersectObjects(gizmos, true);
var invalid;
if (invalidIntersects.length > 0) {
...