<template>
  <div class="preload-source"
       ref="preload"
       v-show="false">
    <!-- <img src="../images/default_common_img@2x.png"
         alt=""
         :name="pre+'IMG_ERR'"> -->
    <img alt=""
         :name="pre+'IMG_ERR'">
  </div>
</template>

<script>
export default {
  name: 'PreLoadSource',
  data() {
    return {
      pre: 'PRE_'
    };
  },
  mounted() {
    this.$nextTick(() => {
      let img;
      this.$refs['preload'].childNodes.forEach((item) => {
        img = new Image();
        img.src = item.src;
        img.onload = () => {
          // 存入sessionStorge
          sessionStorage.setItem(item.name, this.getBase64Image(img));
        };
      });
    });
  },
  methods: {
    getBase64Image(img) {
      const canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, img.width, img.height);
      const ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase();
      const dataURL = canvas.toDataURL('image/' + ext);
      return dataURL;
    }
  }
};
</script>
