こんにちは。
regl (Functional WebGL, GitHub) + React を利用しランダムな点のアニメーションを描いてみました。定期的更新には use-interval (GitHub) を用いました。
App.js
import React from 'react';
import createRegl from 'regl';
import useInterval from 'use-interval';
const App = () => {
const pointSize = 14;
const pointRandom = () =>
[2 * Math.random() - 1, // x
2 * Math.random() - 1, // y
Math.random(), Math.random(), 0]; // r, g, b
const generatePoints = (nPoints) => Array(nPoints).fill(0).map(pointRandom);
const regl = createRegl(document.querySelector('.canvas'));
const frag = `
precision mediump float;
varying vec3 fragColor;
void main() {
gl_FragColor = vec4(fragColor, 1);
}
`;
const vert = `
varying vec3 fragColor;
attribute vec2 pos;
attribute vec3 color;
uniform float pointSize;
void main() {
fragColor = color;
gl_PointSize = pointSize;
gl_Position = vec4(pos, 0, 1);
}
`;
const drawPoints = regl({
frag: frag,
vert: vert,
primitive: 'points',
count: (context, props) => props.points.length,
attributes: {
pos: (context, props) => props.points.map(d => d.slice(0, 2)),
color: (context, props) => props.points.map(d => d.slice(2, 5))
},
uniforms: {
pointSize: pointSize,
points: regl.prop('points')
}
});
const clearRegl = () => regl.clear({
color: [0, 0, 0, 0],
depth: 1
});
let i = 0;
useInterval(() => {
clearRegl();
drawPoints({points: generatePoints((++i%2)*4+2)});
}, 1000);
return <div className='canvas'></div>;
};
export default App;