Three.js 2d plane
by Julien Etienne
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Three.js Shiny Plane with Mouse-controlled Point Light</title>
<style>
body {
margin: 0;
}
canvas {
display: block;
}
</style>
</head>
<body>
<script type="module">
import * as THREE from 'https://threejs.org/build/three.module.js';
// Create scene
const scene = new THREE.Scene();
// Create camera
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
// Create renderer
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Create plane geometry
const planeGeometry = new THREE.PlaneGeometry(10, 10);
const planeMaterial = new THREE.MeshPhongMaterial({ color: 0x888888, shininess: 100 });
const plane = new THREE.Mesh(planeGeometry, planeMaterial);
// Position the plane in front of the camera
plane.position.z = -2;
scene.add(plane);
// Create point light
const pointLight = new THREE.PointLight(0xffffff, 10);
scene.add(pointLight);
// Handle window resizing
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Handle mouse movement
const mouse = new THREE.Vector2();
window.addEventListener('mousemove', (event) => {
// Normalize mouse coordinates to the range [-1, 1]
const x = (event.clientX / window.innerWidth) * 2 ;
const y = -(event.clientY / window.innerHeight) * 2 ;
console.log(x,y)
// Update point light position based on mouse
pointLight.position.set(x, y, 0);
});
// Animation loop
...