resizeImage.js 2.24 KB
import Vue from 'vue'
import { defaultImage } from '@/components/Upload/utils/default'
const getImageSize = function (src) {
    return new Promise((resolve, reject) => {
        const img = new window.Image()
        if (img.complete) {
            resolve(img)
        }
        img.onload = function () {
            resolve(img)
        }
        img.src = src
        img.crossOrigin = '*'
        img.onerror = function (e) {
            reject(e)
        }
    })
}
const image = {
    bind (el, binding) {
    },
    inserted (el, binding) {
        Vue.nextTick(() => {
            let style = el.getBoundingClientRect()
            let outRatio = style.width / style.height
            getImageSize(binding.value).then(res => {
                let width = res.width
                let height = res.height
                let inRatio = width / height > outRatio ? 'height' : 'width'
                if (binding.value) {
                    el.style.backgroundImage = `url(${binding.value})`
                }
                if (inRatio === 'height') {
                    el.style.backgroundSize = '100% auto'
                } else {
                    el.style.backgroundSize = 'auto 100%'
                }
            }).catch(() => {
                el.style.backgroundImage = `url(${defaultImage})`
                el.style.backgroundSize = '100%'
            })
        })
    },
    update (el, binding) {
        Vue.nextTick(() => {
            let style = el.getBoundingClientRect()
            let outRatio = style.width / style.height
            getImageSize(binding.value).then(res => {
                let width = res.width
                let height = res.height
                let inRatio = width / height > outRatio ? 'height' : 'width'
                if (binding.value) {
                    el.style.backgroundImage = `url(${binding.value})`
                }
                if (inRatio === 'height') {
                    el.style.backgroundSize = '100% auto'
                } else {
                    el.style.backgroundSize = 'auto 100%'
                }
            }).catch(() => {
                el.style.backgroundImage = `url(${defaultImage})`
                el.style.backgroundSize = '100%'
            })
        })
    }
}
export default image