랜덤 포인트 애니메이션

안녕하세요.
regl(Functional WebGL, GitHub) + React를 사용하여 랜덤 포인트 애니메이션을 그립니다.정기적인 업데이트에는 GitHubuse-interval가 사용됩니다.

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;

좋은 웹페이지 즐겨찾기