ThreeJs

From ImpVis Wiki
Revision as of 10:16, 2 October 2022 by AbhinandShibu (talk | contribs) (Adding some installation instructions)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Sarmpavi's guide and info: Three.js

Setting up your development environment (installation)

If you are new to programming with javascript and the size of the project is small (maybe a few interactive graphs), I recommend using the online environment as you can get started with it straight away.

Online Installation

- Go to code sandbox and create a free account.

- Fork this repo (the button is on the top right).

Local Installation

- Install Node.js.

- Create a folder where you would like to store the code for the project.

- Navigate to that folder on the command line, then type "npm install three".

- Create a file called index.html and fill it with the following:

<!DOCTYPE html>
<html>

<head>
	<title>My Visualisation</title>
	<meta charset="UTF-8" />
</head>

<body>
	<div id="app"></div>

	<script src="src/index.js">
	</script>
</body>

</html>

- Create a folder inside your directory called src and make a file called index.js, then fill it with the following:

import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import "./styles.css";

let camera, scene, renderer, orbitControls;

init();
animate();

function init() {
  // Making a scene
  scene = new THREE.Scene();

  // Camera
  camera = new THREE.PerspectiveCamera(
    40, // Field of view
    window.innerWidth / window.innerHeight,
    1,
    2000
  );
  camera.position.x = 60;
  camera.position.y = 20;
  camera.position.z = 50;

  // Renderer
  renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);

  // Orbit Controls
  orbitControls = new OrbitControls(camera, renderer.domElement);
  orbitControls.autoRotate = true;
  orbitControls.autoRotateSpeed = 1;

  // Creating and adding ambient light
  const ambientLight = new THREE.AmbientLight(0xffffff, 0.4);
  scene.add(ambientLight);

  // Creating and adding directional light
  const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
  directionalLight.position.set(0, 2, 10);
  scene.add(directionalLight);

  // ADD OBJECTS HERE ------

  // Creating and adding the cube
  const geometry = new THREE.BoxGeometry(10, 10, 10);
  const material = new THREE.MeshStandardMaterial({ color: 0x106b54 });
  const cube = new THREE.Mesh(geometry, material);
  scene.add(cube);

  // -----------------------

  // append the rendered to the dom
  document.body.appendChild(renderer.domElement);

  // render the scene
  renderer.render(scene, camera);
}

function animate() {
  requestAnimationFrame(animate);
  orbitControls.update();
  renderer.render(scene, camera);
}