LoginSignup
4
4

More than 5 years have passed since last update.

[tmlib.js]グラデーション

Posted at

HTML5 Canvasのグラデーションをtmlib.jsで

tmlib.jsでグラデーションを使う時に便利なクラスを紹介します。

線形グラデーション

tm.graphics.LinearGradient を使います。

var gradation = tm.graphics.LinearGradient(0, 0, 100, 100)
    .addColorStopList([
        { offset: 0.0, color: "hsl(  0, 80%, 80%)" },
        { offset: 1.0, color: "hsl(200, 80%, 80%)" },
    ])
    .toStyle();

tm.display.RectangleShape(500, 500, {
    fillStyle: gradation
});

カラーストップ情報を配列で追加できる .addColorStopList() メソッドが便利です。
このメソッドは自分自身を返すので、チェーンメソッド連結できます。

単一のカラーストップを追加する .addColorStop() メソッドも使えます。

最後に .toStyle() メソッドでCanvasGradientオブジェクトに変換し、Canvas描画のスタイルとして適用します。

配列で指定できるので、こんな書き方もできますね。

var gradation = tm.graphics.LinearGradient(0, 0, 500, 500)
    .addColorStopList(Array.range(0, 20).map(function(i) {
        return {
            offset: i / 20,
            color: "hsl({0}, 80%, 80%)".format(360 * i / 20),
        };
    }))
    .toStyle();

ss0.png

動作サンプル

放射グラデーション

放射グラデーションの tm.graphics.RadialGradient クラスも同様の使い方ができます。

var gradation = tm.graphics.RadialGradient(250, 250, 0, 250, 250, 250)
    .addColorStopList(Array.range(0, 20).map(function(i) {
        return {
            offset: i / 20,
            color: "hsla({0}, 80%, 80%, {1})".format(360 * i / 20, 1 - i / 20),
        };
    }))
    .toStyle();

ss1.png

動作サンプル

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