Instanced + properties v2
by tfoller
HTML
<canvas id="main_canvas" style="border: solid 1px red;" width=400 height=300></canvas>
CSS
body {
background: #000;
}
#main_canvas {
background: repeating-linear-gradient(90deg, rgba(80, 40, 70, 1) 0px, rgba(80, 40, 70, 1) 2px, rgba(0, 0, 0, 1) 2px, rgba(0, 0, 0, 1) 4px);
}
JavaScript
import * as THREE from 'https://alikim.com/jsm/three.module.test.js'
import UTL from 'https://alikim.com/jsm/utils.module.js'
const genRNG = (n, beg = 0, end = 1) => {
const mult = end - beg;
const shft = beg;
const rng = [];
for (let i = 0; i < n; i++) rng[i] = shft + mult * UTL.rndF();
return rng;
}
const renderer = new THREE.WebGLRenderer({
antialias: false,
alpha: true,
canvas: document.querySelector('#main_canvas'),
});
renderer.setPixelRatio(window.devicePixelRatio);
const [cw, ch] = [400, 300];
const camera = new THREE.OrthographicCamera(-cw / 2, cw / 2, ch / 2, -ch / 2, 0, 100);
const str_num = 12;
const mat = new THREE.MeshBasicMaterial();
const geo = new THREE.SphereGeometry(1, 16, 16);
const stars = new THREE.InstancedMesh(geo, mat, str_num);
const str_pos = {
x: genRNG(str_num, -cw / 2, cw / 2),
y: genRNG(str_num, -ch / 2, ch / 2)
};
const str = {};
const prs = {
'sz': [5, 10],
'h': [0, 1],
's': [1, 1],
'v': [1, 1],
'op': [0, 1]
};
for (let pr in prs) {
const arr = prs[pr];
str[pr] = genRNG(str_num, arr[0], arr[1]);
}
const matrix = new THREE.Matrix4();
const color = [];
for (let j = 0; j < str_num; j++) {
const sc = str.sz[j];
matrix.makeScale(sc, sc, sc).setPosition(str_pos.x[j], str_pos.y[j], 0);
stars.setMatrixAt(j, matrix);
color.push(...UTL.HSVtoRGB(str.h[j], str.s[j], str.v[j]), str.op[j]);
}
mat.transparent = true;
stars.instanceColor = new THREE.BufferAttribute(new Float32Array(color), 4);
const geo2 = new THREE.PlaneBufferGeometry(250, 250);
const mat2 = new THREE.MeshPhongMaterial();
const clrQuad = new THREE.Mesh(geo2, mat2);
const color2 = [
1, 0, 0, 0.5,
0, 1, 0, 1,
0, 0, 1, 0.5,
1, 0, 1, 1
];
geo2.setAttribute('color', new THREE.Float32BufferAttribute(color2, 4));
mat2.vertexColors = true;
stars.position.set(0, 0, -(prs.sz[1] + 1));
clrQuad.position.set(0, 0, -(prs.sz[1] + 20));
const scene = new THREE.Scene()
.add(stars)
.add(clrQuad);
const light = new...