0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ランダムな点のアニメーション(regl + React 利用)

Last updated at Posted at 2020-06-19

こんにちは。
regl (Functional WebGL, GitHub) + React を利用しランダムな点のアニメーションを描いてみました。定期的更新には use-interval (GitHub) を用いました。

regl.jpg

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;
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?