JSFiddle - React, Tailwind, and code Playground
by tfoller
HTML
<link type="text/css" rel="stylesheet" href="https://alikim.com/_v1_jsm/css/controls.css">
<canvas id="main_canvas" width="500" height="500"></canvas>
<button id="btn">delete index 1 instance</button>
<script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.145.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.145.0/examples/jsm/"
}
}
</script>
CSS
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
background: #112233;
width: 100vw;
height: 100vh;
}
button {
padding: 3px;
margin-left: 10px;
color: #333;
filter: invert(100%);
cursor: pointer;
}
canvas {
display: block;
border: solid 1px grey;
box-sizing: content-box;
margin: 10px;
}
button {
display: block;
margin: 10px 0px 0px 10px;
}
JavaScript
import * as THREE from 'three'
import * as CONTROLS from 'https://alikim.com/_v1_jsm/controls.js'
const get = id => document.getElementById(id);
const canvas = get('main_canvas');
const [w, h] = [canvas.width, canvas.height];
const renderer = new THREE.WebGLRenderer({
antialias: true,
canvas: canvas,
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(w, h);
const [near, far] = [1, 100];
const mid = -0.5 * (near + far);
const camera = new THREE.PerspectiveCamera(45, w / h, near, far);
camera.position.set(3, 4, 3);
camera.lookAt(0, 0, 0);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0.01, 0.01, 0.15);
const lightA = new THREE.AmbientLight(0xff0000, 0.2);
const lightD = new THREE.DirectionalLight(0xffffff, 0.8);
lightD.position.set(20, 30, 100);
scene.add(lightA).add(lightD);
const geo = new THREE.CylinderGeometry(0.5, 0.7, 1, 6);
const mat = new THREE.MeshLambertMaterial();
const size = 3;
const imesh = new THREE.InstancedMesh(geo, mat, size);
// array of matrices
const mtx = new Array(size);
// array of colors
const clr = new Array(size);
for(let i = 0; i < size; i++) {
const pos = new THREE.Vector3(0, 0, i - 1);
const rot = new THREE.Quaternion(0, 0, 0, 1);
const scale = new THREE.Vector3(1, 1 - i * 0.2, 1);
mtx[i] = new THREE.Matrix4().compose(pos, rot, scale);
clr[i] = new THREE.Color(i/4, 1 - i/4, 1);
imesh.setMatrixAt(i, mtx[i]);
imesh.setColorAt(i, clr[i]);
}
scene.add(imesh);
// remove instance
const remove = n => {
if(n >= imesh.count) return;
// delete data from arrays
mtx.splice(n, 1);
clr.splice(n, 1);
// update instance count
imesh.count--;
// re-apply
for(let i = 0; i < imesh.count; i++) {
imesh.setMatrixAt(i, mtx[i]);
imesh.setColorAt(i, clr[i]);
}
imesh.instanceMatrix.needsUpdate = true;
imesh.instanceColor.needsUpdate = true;
};
const render = () => { renderer.render(scene, camera) };
render();
get('btn').addEventListener('click', () =>...