104 부모 태그에 맞춰 img 정렬하기 object-fit: cover 기능 구현
source: categories/study/vue-experiance/vue-experiance_9-99_05.md
104 부모 태그에 맞춰 img 정렬하기 object-fit: cover 기능 구현
<template>
<img ref="ImageObject" :src="url" alt="" :style="imageStyle" />
</template>
<script>
export default {
name: 'ObjectFitImage',
props: {
url: {
type: String,
required: true,
},
width: {
type: String,
required: true,
},
height: {
type: String,
required: true,
},
},
data() {
return {
objectFitStyle: {},
};
},
computed: {
imageStyle() {
return { width: this.width, height: this.height, ...this.objectFitStyle };
},
},
mounted() {
this.$refs.ImageObject.addEventListener('load', this.objectFit);
},
methods: {
// 이미지 사이즈
objectFit(e) {
const targetRect = e.target.getBoundingClientRect();
const naturalRatio = e.target.naturalWidth / e.target.naturalHeight;
const realRatio = targetRect.width / targetRect.height;
if (naturalRatio >= realRatio) {
this.objectFitStyle = {
width: 'auto',
height: '100%',
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
};
} else {
this.objectFitStyle = {
width: '100%',
height: 'auto',
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
};
}
},
},
};
</script>
<style scoped></style>