Vue 2.6でAnimated PNGまたはGIFのアニメーションをコンポネントの再表示・アップデートの時に再起動
UIはアニメーション画像(PNGまたはGIF)を表示する必要があり、一番簡単な方法はimg
タグを使用することです。
問題は、無限ループがない場合、アニメーションが最後のフレームで停止することです。
VueのSFC(シングル・ファイル・コンポネント)
正方形のコンテナの中央にアニメーション画像を表示します。
コンテナ
ここでは、コンテナのposition
スタイルプロパティをrelative
に設定するだけです:
<div
style="position: relative; background-color: #ECECEC; height: 150px; width: 150px; overflow: hidden;"
>
</div>
※ また、アニメーションがコンテナの境界を越えないように、overflow
をhidden
に設定しました。
画像
画像を中央に配置
- 画像のposition
スタイルプロパティをabsolute
に設定し、コンテナの中央に配置します。
- 画像を半分のサイズに変換して、画像中央をコンテナの中央に配置します。
<img
style="
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
"
/>
画像のサイズ変更
-
height
の高さにscale
のスケールファクターを掛けます -
width
の幅にscale
のスケールファクターを掛けます
<img
...
:height="animation.height * animation.scale"
:width="animation.width * animation.scale"
/>
画像の設定
- アニメーション画像のパスを設定します。
-
img
タグへのVue
のref
を設定します。
<img
ref="image2D"
...
:src="animation.image_path"
...
/>
コンポネントのコード
コンポーネントのprops
から画像のパス、高さ、幅、スケールを取得する必要があります
<script>
import Vue from 'vue'
export default {
name: "Sample",
props: {
animation: {
required: true
},
},
}
</script>
mountedのライフサイクルフック
コンポーネントがレンダリングされるときに呼び出されます。
アニメーションを再開するには、画像コンテンツを非同期でリセットする必要があることに注意してください。
mounted() {
requestAnimationFrame(() => {this.$refs.image2D.src = this.$refs.image2D.getAttribute('src')});
},
updatedのライフサイクルフック
一部のプロパティ情報が別のコンポーネントで変更されたときに呼び出されます。 私プロジェクトでは、画像の縮尺を変更するためのボタンを備えたコンポーネントがありました。
アニメーションを再開するには、画像コンテンツをリセットする必要があります。
updated() {
this.$refs.image2D.src = this.$refs.image2D.getAttribute('src')
}
まとめたコード
最後に、サンプルコードの全て:
</template>
<div
style="position: relative; background-color: #ECECEC; height: 150px; width: 150px; padding: 25%; overflow: hidden;"
>
<img
ref="image2D"
style="
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
"
:src="animation.image_path"
:height="animation.height * animation.scale_y"
:width="animation.width * animation.scale_x"
/>
</div>
</template>
<script>
import Vue from 'vue'
export default {
name: "Sample",
props: {
animation: {
required: true
},
},
mounted() {
requestAnimationFrame(() => {this.$refs.image2D.src = this.$refs.image2D.getAttribute('src')});
},
updated() {
this.$refs.image2D.src = this.$refs.image2D.getAttribute('src')
}
};
</script>