Show grid in object
Stencils: How to show grid in object in threejs
by mmalex
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/100/three.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<button id="btn" onclick="fixZFighting()" style="position: fixed; top: 12px; left: 12px;">
Fix z-fighting
</button>
CSS
body {
overflow: hidden;
padding: 0;
margin: 0;
}
JavaScript
var camera, scene, renderer, controls, line, cube;
init();
animate();
function init() {
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({
alpha: true,
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x555555, 1);
renderer.sortObjects = true;
document.body.appendChild(renderer.domElement);
camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
scene.add(camera);
camera.position.x = 2000;
camera.position.y = 2000;
camera.position.z = 2000;
// white spotlight shining from the side, casting a shadow
let spotLight = new THREE.SpotLight(0xffffff);
spotLight.position.set(1, 1200, 2);
spotLight.castShadow = true;
spotLight.shadow.mapSize.width = 1024;
spotLight.shadow.mapSize.height = 1024;
spotLight.shadow.camera.near = 500;
spotLight.shadow.camera.far = 4000;
spotLight.shadow.camera.fov = 30;
// assign light to layer#1
spotLight.layers.set(1);
scene.add(spotLight);
controls = new THREE.OrbitControls(camera);
let gridHelper = new THREE.GridHelper(1000, 10);
gridHelper.layers.set(0);
scene.add(gridHelper);
let lineMaterial = new THREE.LineBasicMaterial({
color: 0x00ffff
});
let lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push(
new THREE.Vector3(300, 750 / 2, -300),
new THREE.Vector3(300, 750 / 2, 300),
new THREE.Vector3(-300, 750 / 2, 300),
new THREE.Vector3(-300, 750 / 2, -300),
new THREE.Vector3(300, 750 / 2, -300),
);
line = new THREE.Line(lineGeometry, lineMaterial);
line.rotation.z = Math.PI / 12;
line.rotation.x = Math.PI / 4;
line.updateMatrix();
// assign line to layer#1
line.layers.set(1);
scene.add(line);
let cubeMaterial = new...