How to Import Three.js
by Kuligaposten Jan 22 2023
Import Three.js and addons from a CDN
How to Import Three.js from a CDN and Build a 3D Scene with Stars and Backgrounds
Three.js is a powerful JavaScript 3D library, and the best part is you don't need to install anything or use a build tool to start experimenting. You can use it directly from a CDN with ES Modules in the browser!
In this guide, we’ll walk through how to:
- Import Three.js and addons from a CDN
- Create a rotating cube, sphere, and torus
- Add a swirling starfield in 3D
- Load a skybox and background image
- Animate the camera smoothly using GSAP
1. Importing Three.js via CDN
Start with a basic HTML file. We’ll use three.module.js and import it using a <script type="module">. Add this to your <head> or before closing <body>:
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.175.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.175.0/examples/jsm/"
}
}
</script>
Then, in your JavaScript file (e.g. app.mjs):
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
2. Set Up the Scene
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000,
);
camera.position.set(2, 2, 5);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
Add lighting, ground, and controls:
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
scene.add(new THREE.AmbientLight(0xffffff, 0.5));
const dirLight = new THREE.DirectionalLight(0xffffff, 1.2);
dirLight.position.set(5, 5, 5);
scene.add(dirLight);
3. Add Objects
const cube = new THREE.Mesh(
new THREE.BoxGeometry(),
new THREE.MeshStandardMaterial({ color: 0x3399ff }),
);
cube.position.y = 1;
scene.add(cube);
const sphere = new THREE.Mesh(
new THREE.SphereGeometry(0.5, 32, 32),
new THREE.MeshStandardMaterial({ color: 0xff5500 }),
);
sphere.position.set(-2, 1, 0);
scene.add(sphere);
const torus = new THREE.Mesh(
new THREE.TorusGeometry(0.5, 0.15, 16, 100),
new THREE.MeshStandardMaterial({ color: 0x00ccff }),
);
torus.position.set(2, 1, 0);
scene.add(torus);
4. Create a Swirling Starfield
let starfield;
function createStarfield(count = 2000, radius = 100) {
if (starfield) scene.remove(starfield);
const positions = [];
for (let i = 0; i < count; i++) {
const theta = Math.random() * 2 * Math.PI;
const phi = Math.acos(2 * Math.random() - 1);
const r = radius * Math.cbrt(Math.random());
positions.push(
r * Math.sin(phi) * Math.cos(theta),
r * Math.sin(phi) * Math.sin(theta),
r * Math.cos(phi),
);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3),
);
const texture = new THREE.TextureLoader().load("/assets/img/star.png");
const material = new THREE.PointsMaterial({
size: 0.7,
map: texture,
transparent: true,
depthWrite: false,
blending: THREE.AdditiveBlending,
});
starfield = new THREE.Points(geometry, material);
scene.add(starfield);
}
createStarfield();
In the animation loop, swirl the stars:
function animate() {
requestAnimationFrame(animate);
if (starfield) {
const pos = starfield.geometry.attributes.position;
for (let i = 0; i < pos.count; i++) {
const x = pos.getX(i);
const z = pos.getZ(i);
const angle = Math.atan2(z, x) + 0.0005;
const r = Math.sqrt(x * x + z * z);
pos.setXYZ(i, r * Math.cos(angle), pos.getY(i), r * Math.sin(angle));
}
pos.needsUpdate = true;
}
cube.rotation.y += 0.01;
torus.rotation.x += 0.01;
torus.rotation.y += 0.02;
controls.update();
renderer.render(scene, camera);
}
animate();
5. Add a Background Image or Skybox
const milkyWayTexture = new THREE.TextureLoader().load(
"/assets/img/milkyway.webp",
);
scene.background = milkyWayTexture;
Or load a cube map skybox:
const skybox = new THREE.CubeTextureLoader().load([
"/assets/img/px.webp",
"/assets/img/nx.webp",
"/assets/img/py.webp",
"/assets/img/ny.webp",
"/assets/img/pz.webp",
"/assets/img/nz.webp",
]);
// To switch:
scene.background = skybox;
6. Smooth Camera Tweens with GSAP
Add GSAP in your HTML:
<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.2/dist/gsap.min.js"></script>
Then animate camera and controls:
gsap.to(camera.position, {
duration: 1.5,
x: 0,
y: 2,
z: 20,
ease: "power2.out",
});
gsap.to(controls.target, {
duration: 1.5,
x: 0,
y: -5,
z: 0,
ease: "power2.out",
onUpdate: () => controls.update(),
});
With this setup, you can mix and match backgrounds, animate your camera, and create immersive real-time scenes — all using just HTML, a CDN, and a bit of JS.
Happy galaxy building!