【jQuery】背景に波紋アニメーションを実装する方法

サイトの背景に波紋アニメーションを実装したい。
本記事ではJavaScriptのライブラリjQueryとjQuery Ripplesを使ってこのような悩みを解決します。
ライブラリを読み込み・ダウンロード

まずはjQueryとjQuery Ripplesを実装環境に読み込みます。
jQuery Ripplesは以下サイト様よりダウンロード可能です。
公式サイト
https://sirxemic.github.io/jquery.ripples/
GitHub
https://github.com/sirxemic/jquery.ripples/
ダウンロードしたらscriptタグを使って環境に読み込みます。
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="js/jquery.ripples-min.js"></script>
波紋の実装コード
<style>
/*背景のスタイル*/
div.ripples {
background-color: #f5f3ee;
width: 100%;
height: 100vh;
}
</style>
<!-- 波紋背景 -->
<div class="div ripples">
</div>
<!-- ライブラリを読み込み -->
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="js/jquery.ripples-min.js"></script>
<!-- 実装コード -->
<script>
// マウスでホバーした箇所に波紋を出す
$("div.ripples").ripples({
// 波紋の広かる速さ
resolution: 512,
// 波紋の大きさ
dropRadius: 40,
// 波紋の揺れの量
perturbance: 0.04,
});
</script>
波紋の実装コード例です。
以下コードだけで波紋を出したい箇所にホバー・クリックすると波紋が出ます。
$("波紋を出したいhtmlタグ名").ripples();
さらに以下オプションを追加するだけで波紋の大きさや揺れなどを調整する事が可能です。
// 波紋の広かる速さ
resolution
// 波紋の大きさ
dropRadius
// 波紋の揺れの量
perturbance
波紋を自動で出力する
// ランダムで波紋を自動で出す
setInterval(function () {
var $el = $("div.ripples");
var x = Math.random() * $el.outerWidth();
var y = Math.random() * $el.outerHeight();
// 波紋の大きさ
var dropRadius = 30;
// 波紋の広かる速さ
var resolution = 0.2;
// 波紋の揺れの量
var perturbance = 0.04;
var strength = 0.04 + Math.random() * 0.04;
$el.ripples("drop", x, y, dropRadius, resolution, perturbance, strength);
}, 400);
setInterval関数などを組み合わせて使う事で波紋をランダムに出力する事が可能になります。
以上で実装完了です。
まとめ
jQueryで背景に波紋アニメーションを実装する方法について紹介しました。
以上で解説を終わります。
目次