お仕事で要望があって作ったのでメモ。
目次
要望
div要素内の背景に、ランダムに複数のラインを表示させるアニメーションを表示する。ラインはレーザー光線をイメージさせるような見栄えとエフェクトがほしい。
その他補足、仕様
- 同時に表示させるラインは3つ
- それぞれのアニメーションの開始時期を0.5秒毎ずらす。
- ラインはレーザーのようなエフェクトをCSSでつける。
- ラインの動きは平行ではなく、360度方向からランダムに開始される。
- アニメーションはループさせる
コードサンプル
HTML
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Lines Animation</title>
<link rel="stylesheet" href="laser.css">
</head>
<body>
<div class="laser-wrap" id="lineContainer"></div>
<script src="laser-anime.js"></script>
</body>
</html>
CSS(laser.css)
.laser-wrap{
position: relative;
width: 100%;
height: 300px;
border: 1px solid black;
overflow: hidden;
}
.line {
position: absolute;
height: 2px;
background: linear-gradient(90deg, rgba(255,0,0,0) 0%, rgba(255,0,0,1) 50%, rgba(255,0,0,0) 100%);
box-shadow: 0 0 5px rgba(255,0,0,0.7);
animation: slide 1s forwards; /* アニメーションが終了した後のスタイルを保持する */
}
@keyframes slide {
0% {
width: 0%;
opacity: 1;
}
100% {
width: 150%; /* コンテナの中心から外側に向かって伸びるための150%の幅を指定 */
opacity: 0;
}
}
@keyframes slide {
to {
transform: translate(100%);
}
}
/* ラインをレーザーっぽく装飾 */
.line {
position: absolute;
height: 2px;
background: linear-gradient(90deg, rgba(255,0,0,0) 0%, rgba(255,0,0,1) 50%, rgba(255,0,0,0) 100%); /* レーザー光線のようなグラデーション */
box-shadow: 0 0 5px rgba(255,0,0,0.7); /* レーザーの光らしさを強調するためのぼかし */
animation: slide 5s infinite;
}
JavaScript(laser-anime.js)
document.addEventListener("DOMContentLoaded", function () {
const container = document.getElementById('lineContainer');
const numberOfLines = 3; // ラインの数を3つに変更
for (let i = 0; i < numberOfLines; i++) {
createRandomLine(container);
}
});
function createRandomLine(container) {
const line = document.createElement('div');
line.className = 'line';
const randomYPosition = Math.random() * container.offsetHeight;
const randomXPosition = Math.random() * container.offsetWidth;
const randomWidth = Math.random() * container.offsetWidth / 2 + container.offsetWidth / 4; // 最小50%、最大75%の幅
const randomAngle = Math.random() * 360; // 0 to 360 degrees
line.style.top = randomYPosition + 'px';
line.style.left = randomXPosition + 'px';
line.style.width = randomWidth + 'px';
line.style.transform = `rotate(${randomAngle}deg)`; // Set rotation
container.appendChild(line);
}