LoginSignup
2
2

More than 3 years have passed since last update.

regl+VueでWebGLのシェーダを簡単に扱う

Posted at

概要

reglはWebGL APIのwrapperのようなライブラリ。生のWebGLに近い自由度を保ちつつ、格段にシンプルな記述を可能にする。
ここでは、Vue (+TypeScript) 環境でreglを用いた描画を行うシンプルな方法を記載する。

(↓のVue版に相当。reglの説明などはそちらを参照。)

※ VueもTypeScriptも初心者なので、より良い方法があったら教えてください。

Vueでreglを扱う

もともとNuxt.jsを利用して/pages以下に置くことを想定したコードだが、Nuxt.jsを使わなくても(ほぼ?)同じだと思う(詳しくない)。

regl.vue
<template>
  <div id="regl" style="width: 100%; height: 100%"></div>
</template>

<script lang="ts">
import Vue from 'vue'
import createRegl from "regl";

const frag = `
precision mediump float;
uniform vec4 color;
void main() {
  gl_FragColor = color;
}`
const vert = `
precision mediump float;
attribute vec2 position;
void main() {
  gl_Position = vec4(position, 0, 1);
}`

export default Vue.extend({
  data () {
    return {
      regl: {} as createRegl.Regl
    }
  },
  mounted () {
    this.regl = createRegl("#regl")
    const drawTriangle = this.regl({
      frag: frag,
      vert: vert,
      attributes: {
        position: [[0, -1], [-1, 0.5], [1, 1]] // No need to flatten
      },
      uniforms: {
        color: this.regl.prop('color')
      },
      count: 3 // Number of vertices to draw in this command
    })
    this.regl.frame(({ time }) => {
      this.regl.clear({
        color: [0, 0, 0, 0],
        depth: 1
      });
      drawTriangle({
        color: [
          Math.cos(time * 1.0),
          Math.sin(time * 0.8),
          Math.cos(time * 3.0),
          1
        ]
      });
    })
  },
  destroyed () {
    this.regl.destroy()
  }
})
</script>

マウントされたタイミングでdiv#regl要素に関してreglのインスタンスを作成し、三角形の描画を行っている。シェーダは文字列として直接記述しているが、外部ファイルに分離したものをraw-loaderで読み込んでも良い。

2
2
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
2
2