1
2

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.

GLSLで球体の頂点の色をグラデーションにしてみる

Posted at

やりたいこと

GLSLでキャンバス上に3Dの球体を描く。
頂点ごとに色を変えてグラデーションをつくる。

基本となるコード

// 頂点座標の定義(球体状にする) @@@
        const VERTEX_COUNT  = 100; // 頂点の個数
        const VERTEX_RADIUS = 1.0; // 球体の半径
        this.position = [];        // 頂点座標
        this.color = [];           // 頂点色
        for(let i = 0; i < VERTEX_COUNT; ++i){
            // 変数 i を元にラジアンを求める(XZ 平面をぐるりと一周するためのラジアン)
            const iRad = (i / VERTEX_COUNT) * Math.PI * 2.0;
            // 求めたラジアンからサインとコサインを作る
            const x = Math.sin(iRad);
            const z = Math.cos(iRad);
            for(let j = 0; j < VERTEX_COUNT; ++j){
                // 変数 j を元にラジアンを求める(上から下までぐるっと半周するためのラジアン)
                const jRad = j / VERTEX_COUNT * Math.PI;
                const radius = Math.sin(jRad);
                const y      = Math.cos(jRad);
                // 計算結果を元に XYZ 座標を決める
                this.position.push(
                    x * VERTEX_RADIUS * radius,
                    y * VERTEX_RADIUS,
                    z * VERTEX_RADIUS * radius,
                );
                this.color.push(i / VERTEX_COUNT, j / VERTEX_COUNT, 0.1, 1.0);
            }
        }

this.color.pushの中身を少しづつ変えて、カラーバッファに送る色を変える。

例1:0.1でまわす→オレンジと緑になる

スクリーンショット 2021-01-11 19.22.36.png


this.color.push(i / VERTEX_COUNT, j / VERTEX_COUNT, 0.1, 1.0);

0.5にする場合

赤系→緑系でカラフルなグラデになる

スクリーンショット 2021-01-11 19.14.49.png

this.color.push(i / VERTEX_COUNT, j / VERTEX_COUNT, 0.5, 1.0);

例3: 1.0にする場合

ピンクと青の球になる

スクリーンショット 2021-01-11 19.32.04.png

this.color.push(i / VERTEX_COUNT, j / VERTEX_COUNT, 1.0, 1.0);

1.0以上は色が変わらない。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?