📚
SVGアニメーション(ASVG)が流行ってほしい
なんでASVGが流行って欲しいのか?
設計書や説明資料を書いていると図を書くことは多々ある
もちろんUMLに準拠した方が良いこともある
あ、でも図は動いたほうがわかりやすいのかもって思ったので
できるならシンプルな記述で図を動かせないかなぁっと思ったのでまとめました。
SVGアニメーション
SVG(Scalable Vector Graphics)は、画像だけでなくアニメーションも可能な強力なフォーマットです。
線とか簡易図形を表すなら丁度いいくらいのシンプルさなのではと(主観)
ここでは CSS と JavaScript によって SVG をアニメーションさせる方法を、
「何ができるのか」と「記述例」のセットで一つのファイルにまとめます。
※元々SVGにあるSMILは非推奨になってしまったのでここでは省きます。
✅ CSSによるアニメーション
CSSを使えば、シンプルで軽量なアニメーションが可能です。
1. 透明度の変化(点滅など)
<style>
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0.2; }
}
circle {
animation: blink 1s infinite;
}
</style>
<svg width="100" height="100">
<circle cx="50" cy="50" r="30" fill="red" />
</svg>
2. 回転アニメーション
<style>
@keyframes rotate {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
circle {
transform-origin: 50% 50%;
animation: rotate 2s linear infinite;
}
</style>
<svg width="100" height="100">
<circle cx="50" cy="50" r="30" fill="blue" />
</svg>
3. 線を描くようなアニメーション(stroke-dasharray)
<style>
path {
stroke: black;
stroke-width: 2;
fill: none;
stroke-dasharray: 300;
stroke-dashoffset: 300;
animation: draw 2s forwards;
}
@keyframes draw {
to { stroke-dashoffset: 0; }
}
</style>
<svg width="100" height="100">
<path d="M10,80 C40,10 65,10 95,80" />
</svg>
✅ JavaScriptによるアニメーション
JavaScriptではSVGの属性を動的に変更することで柔軟なアニメーションが可能です。
1. オブジェクトを横に動かす
<svg width="300" height="100">
<circle id="ball" cx="20" cy="50" r="10" fill="red" />
</svg>
<script>
const ball = document.getElementById("ball");
let x = 20;
function move() {
x += 1;
if (x > 280) x = 20;
ball.setAttribute("cx", x);
requestAnimationFrame(move);
}
move();
</script>
2. 回転アニメーション(transform属性)
<svg width="200" height="200">
<rect id="box" x="80" y="80" width="40" height="40" fill="blue" />
</svg>
<script>
const box = document.getElementById("box");
let angle = 0;
function rotate() {
angle += 2;
box.setAttribute("transform", `rotate(${angle}, 100, 100)`);
requestAnimationFrame(rotate);
}
rotate();
</script>
3. マウスに追従するアニメーション
<svg width="300" height="300">
<circle id="follow" cx="150" cy="150" r="10" fill="green" />
</svg>
<script>
const circle = document.getElementById("follow");
document.addEventListener("mousemove", (e) => {
const rect = circle.closest("svg").getBoundingClientRect();
circle.setAttribute("cx", e.clientX - rect.left);
circle.setAttribute("cy", e.clientY - rect.top);
});
</script>
✅ CSSとJavaScriptの使い分けまとめ
やりたいこと | CSS | JavaScript |
---|---|---|
色や透明度の変化 | ◎ | ◎ |
回転・拡大・移動 | ◎ | ◎ |
線の描画 | ◎ | ◎ |
ユーザー操作との連動 | △ | ◎ |
条件分岐・細かい制御 | △ | ◎ |
繰り返しアニメーション | ◎ | ◎ |
webで動作を見るのも簡単だし
シンプルすぎるのが企画書とかには物足りないってなるとライブラリを検討となるのかも・・・
Discussion