LoginSignup
4
3

More than 5 years have passed since last update.

ボールがビリヤードのように跳ね回るアニメーションライブラリ

Posted at

a.png
Web ページ上で「ボールがビリヤードのように跳ね回るアニメーション」を簡単に実装できる JavaScript ライブラリを作りました。
作ったものの、どこにも紹介せずに放置していたのでちょっと記憶がアレですが…。

概要

単純な Canvas アニメーションです。
ライブラリを読み込んだら new して終わり。 API は停止/再開くらいです。

使用例

詳しくは GitHub かデモの HTML を覗いてみてください。

  • デフォルト
    自動生成された canvas 要素が document.body に追加されます。
<script src="./billiards.min.js"></script>
<script>
new Billiards({});
</script>
  • 既存の canvas 要素を指定する
<canvas class="canvas"></canvas>
<script>
new Billiards({
  'canvas': document.querySelector('.canvas')
});
</script>
  • 親要素を指定して canvas 要素を自動生成する
<div class="canvas-container"></div>
<script>
new Billiards({
  'parent': document.querySelector('.canvas-container')
});
</script>
  • Canvas のサイズと背景色を指定する
new Billiards({
  'width': '640',
  'height': '480',
  'fillStyle': 'rgba(0, 0, 0, 0.25)'
});
  • Canvas を自動的にウィンドウサイズに合わせる
new Billiards({
  'fitToWindow': true
});

自動的に親要素のサイズに合わせる fitToParentWfitToParentH もあります。

  • スプライトの詳細設定
    詳しくは こちら。 RGBA 値・半径・速度は [ 最小値, 最大値 ] の範囲でランダムに決定されます。
    なお、半径 r はピクセル指定ではなく、 Canvas のサイズに対する割合を指定します。
new Billiards({
  'number': 8,
  'r': [ 0.1, 0.2 ],
  'color': {
    'r': [ 192, 255 ],
    'g': [ 128, 255 ],
    'b': [ 0, 255 ],
    'a': [ 1.0, 1.0 ]
  },
  'composite': 'lighter',
  'velocity': [ 1.0, 2.0 ]
});
  • 跳ね返らせない
new Billiards({
  'rebound': false
});
  • 衝突させない(すり抜ける)
new Billiards({
  'collide': false
});
  • アニメーションループの手動設定
    既存の requestAnimationFrame に組み込みたい時に。
const billiards = new Billiards({
  'autoPlay': false
});
const update = () => {
  requestAnimationFrame(() => {
    billiards.update();
    update();
  });
};
  • 手動レンダリング
    画像を描画したい時に。 billiards がインスタンス、 billiards._ が設定、 sprite が現在のスプライトです。
new Billiards({
  'render': (billiards, sprite) => {
    billiards.context.fillStyle = sprite.color;
    billiards._.composite && (billiards.context.globalCompositeOperation = billiards._.composite);
    billiards.context.beginPath();
    billiards.context.arc(sprite.x, sprite.y, sprite.r, 0, Math.PI * 2);
    billiards.context.closePath();
    billiards.context.fill();
  }
});

ところで

なんで私ドキュメントとかエセ英語で書いたんでしょうね。

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