LoginSignup
2
3

More than 3 years have passed since last update.

Vue.jsでブラーエフェクト付きの画像遅延ローディング

Posted at

概要

  1. lqip-loaderを使って低解像度版の画像を生成する
  2. vue-lazyloadで、1で生成した低解像度の画像をローディング時の画像として用いる
  3. 遷移時のアニメーションはcssのtranstionを使う

やりたいこと

example.gif

こんな感じで画像を遅延ローディングするときのプレースホルダーにブラーがかかった画像を使いたい!

方法

lqip-loaderを導入する

lqip-loaderは低解像度版の画像を出力するためのwebpackのローダーです。まずはこのツールを導入します。

npm install --save-dev lqip-loader

vue-cliを使ってプロジェクトを作成した場合、vue.config.jsに次のように記述します。

vue.config.js
module.exports = {
  chainWebpack: config => {
    const imagesRule = config.module.rule('images');

    imagesRule.uses.clear();

    imagesRule
      .use('lqip-loader')
      .options({
        path: '/media',
        base64: true,
        palette: false
      })
      .loader('lqip-loader');
  }
};

webpackをそのまま使っている場合は、公式のREADMEを参考に設定してください。

Vue-Lazyloadを導入する

Vue-Lazyloadはリソースの遅延ロードを行うためのVue.js用モジュールです。

公式のREADMEの通りに導入しましょう。

画像を利用する

例として、画像を遅延ロードするコンポーネントLazyImageを実装します。

LazyImage.vue
<template>
    <div class="lazy-image" v-lazy-container="{ selector: 'img' }">
        <img :data-src="img.src"
             :data-loading="img.preSrc"
        >
    </div>
</template>

<script>
  export default {
    name: 'LazyImage',
    props: {
      img: {
        type: Object,
        required: true,
      },
    },
  }
</script>

3,4行目に書いたように、lqip-loaderが出力した低解像度の画像はpreSrcプロパティ1、本来の画像のパスはsrcプロパティで取得できます。

このコンポーネントにimgを渡すときは、次のように記述します。

App.vue
<lazy-image :img="require('./img/example.png')" />

スムーズに遷移する

遷移のアニメーションにはcssが使えます。

cssのfilterでblurをかけ、画像のロードが終了したときにfilterを外せば良いです。あとは好きにtransitionをかけましょう。

lazy-img > img {
  filter: blur(25px);
  transition: all .2s;

  &[lazy=loaded] {
    filter: none
  }
}

参考


  1. base64エンコードされた画像そのものが入っています。 

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3