ThreeJS — The simplest scene you can create

npm install three
  • A link to the style.css file
<link rel=”stylesheet” href=”./style.css”>
  • A <canvas> element, that will be referenced in the main.js file later
<canvas class=”webgl”>
<p>Your browser doesn’t support WebGL</p>
</canvas>
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8" />
<link rel=”icon” type=”image/svg+xml” href=”favicon.ico” />
<link rel=”stylesheet” href=”./style.css”> <title>Vite ThreeJS App</title>
</head>
<body>
<canvas class=”webgl”>
<p>Your browser doesn’t support WebGL</p>
</canvas>
<script type=”module” src=”./main.js”></script>
</body>
</html>
* {
margin: 0;
padding: 0;
}
html, body {
background: transparent;
overflow: hidden;
}
.webgl {
position: fixed;
top: 0;
left: 0;
outline: none;
}
import * as THREE from 'three'
// Get the canvas
const canvas = document.querySelector('canvas.webgl')
// Scene
const scene = new THREE.Scene()
// Camera
const camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.set(-5, 3, 5)
camera.lookAt(new THREE.Vector3(0, 0, 0))
scene.add(camera)
// Create a Cube
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 })
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)
// Add a light
const light = new THREE.DirectionalLight(0xffffff, 1)
light.position.set(-1, 3, 4)
scene.add(light)
// Create the Renderer
const renderer = new THREE.WebGLRenderer( { canvas : canvas } )
renderer.setSize(window.innerWidth, window.innerHeight)
// Render the Scene
renderer.render(scene, camera)
  • the camera orbit controls
  • the animate() function
  • the event listener to resize the window and update the scene

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Robe Santoro

Robe Santoro

3 Followers

Motion Designer with over ten years of experience in 3d Animation, Projection-Mapping, AR-VR-XR, electronics, and the makers’ world. Wannabe Creative Coder…