AMP Htmlでのgifアニメーションの書き方とamp-img
とamp-anim
の違いについて書きます。
AMP Htmlでgifアニメーションを表示する方法を調べてみると、amp-anim
を使ってgifアニメーションを表示する方法が出て来ます。
しかしamp-img
でもgifアニメーションを表示することはできます。だとするとamp-anim
はなんのためにあるのか、amp-img
との違いは何か。という話です。
gifアニメーション表示サンプルコード(amp-img
とamp-anim
両方)
実際に書いてみるとamp-anim
でもamp-img
でも同じようにgifアニメーションが表示されるのがわかります。
<!doctype html>
<html ⚡>
<head>
<meta charset="utf-8">
<script async src="https://cdn.ampproject.org/v0.js"></script>
<script async custom-element="amp-anim" src="https://cdn.ampproject.org/v0/amp-anim-0.1.js"></script>
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<link rel="canonical" href="https://ampbyexample.com/components/amp-anim/">
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
</head>
<body>
<h2>amp-animで表示するgifアニメーション</h2>
<amp-anim width="245" height="300" src="/img/gopher.gif">
</amp-anim>
<h2>amp-imgで表示するgifアニメーション</h2>
<amp-img width="245" height="300" src="/img/gopher.gif">
</amp-img>
</body>
</html>
※ AMPのPlaygroundを開いてコードを貼り付けると、実際に動いてる様子が確認できます。
amp-img
とamp-anim
の違い
-
amp-anim
はプレイスホルダー(gifが表示されるまでの間に表示する画像)を設定できる -
amp-anim
はCPUの使用率を節約できる
Thus, the difference currently is really performance thing. If we could pause animation for GIF, we'd do that. But for now,
amp-anim
allows us to reduce CPU usage and GPU vetoing when it's off screen.参考: https://github.com/ampproject/amphtml/pull/8116#issuecomment-287202023
結論
私はプレースホルダーを設定する予定がないのでわざわざamp-anim
を使うことはないと思いamp-img
を採用しました。
amp-img
とamp-anim
がいずれ統合されるような気もしますし!