JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://threejs.org/build/three.min.js"></script>
<div id="info">PointCloud with Custom, Dynamic Attribute</div>
<script type="x-shader/x-vertex" id="vertexshader">
attribute float alpha;
varying float vAlpha;
void main() {
vAlpha = alpha;
vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
gl_PointSize = 16.0;
gl_Position = projectionMatrix * mvPosition;
}
</script>
<script type="x-shader/x-fragment" id="fragmentshader">
uniform vec3 color;
varying float vAlpha;
void main() {
gl_FragColor = vec4( color, vAlpha );
}
</script>
CSS
body {
color: #ffffff;
font-family:Monospace;
font-size:13px;
text-align:center;
font-weight: bold;
background-color: #000000;
margin: 0px;
overflow: hidden;
}
#info {
color: #fff;
position: absolute;
top: 0px; width: 100%;
padding: 5px;
z-index:100;
}
JavaScript
// PointCloud with Custom, Dynamic Attribute
var renderer, scene, camera, cloud, uniforms, attributes;
init();
animate();
function init() {
// renderer
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
// scene
scene = new THREE.Scene();
//camera
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 400;
// attributes
attributes = {
alpha: { type: 'f', value: [] },
};
// uniforms
uniforms = {
color: { type: "c", value: new THREE.Color( 0x00ff00 ) },
};
// point cloud material
var shaderMaterial = new THREE.ShaderMaterial( {
uniforms: uniforms,
attributes: attributes,
vertexShader: document.getElementById( 'vertexshader' ).textContent,
fragmentShader: document.getElementById( 'fragmentshader' ).textContent,
transparent: true
});
// point cloud geometry
var geometry = new THREE.SphereGeometry( 100, 16, 8 );
// point cloud
cloud = new THREE.PointCloud( geometry, shaderMaterial );
for( var i = 0; i < cloud.geometry.vertices.length; i ++ ) {
// set alpha randomly
attributes.alpha.value[ i ] = Math.random();
}
scene.add( cloud );
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
for( var i = 0; i < attributes.alpha.value.length; i ++ ) {
// dynamically change alphas
attributes.alpha.value[ i ] *= 0.995;
if ( attributes.alpha.value[ i ] < 0.2 ) {
attributes.alpha.value[ i ] = 1.0;
}
}
attributes.alpha.needsUpdate = true; // important!
cloud.rotation.x += 0.005;
cloud.rotation.y += 0.005;
renderer.render( scene, camera );
}