Last active
August 12, 2020 15:23
-
-
Save isuke/8d837d2dd62e3986eb5e7808093bab13 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template lang="pug"> | |
.flexible-image(:style="{width: width + unit, height: height + unit}") | |
img.image(:src="imageUrl" :style="{width: fixedWidth + unit, height: fixedHeight + unit}") | |
</template> | |
<script> | |
export default { | |
props: { | |
imageUrl: { | |
type: String, | |
required: true, | |
}, | |
width: { | |
type: Number, | |
required: true, | |
}, | |
height: { | |
type: Number, | |
required: true, | |
}, | |
unit: { | |
type: String, | |
required: false, | |
default: 'px', | |
}, | |
}, | |
data: function() { | |
return { | |
image: undefined, | |
fixedWidth: undefined, | |
fixedHeight: undefined, | |
} | |
}, | |
computed: { | |
aspectRatio: function() { return this.width / this.height } | |
}, | |
methods: { | |
loadImage: function() { | |
this.image = new Image() | |
this.image.onload = function() { this.calcLength() } | |
}, | |
calcLength: function() { | |
imageAspectRatio = this.image.width / this.image.height | |
if (this.aspectRatio < imageAspectRatio) { | |
this.fixedWidth = null | |
this.fixedHeight = this.height | |
} else { | |
this.fixedWidth = this.width | |
this.fixedHeight = null | |
} | |
} | |
}, | |
mounted: function() { | |
this.loadImage() | |
} | |
} | |
</script> | |
<style lang="scss" scoped> | |
.flexible-image { | |
position: relative; | |
overflow: hidden; | |
> .image { | |
position: absolute; | |
top: 50%; | |
left: 50%; | |
transform: translate(-50%, -50%); | |
} | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment