Skip to content

Instantly share code, notes, and snippets.

@isuke
Last active August 12, 2020 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isuke/8d837d2dd62e3986eb5e7808093bab13 to your computer and use it in GitHub Desktop.
Save isuke/8d837d2dd62e3986eb5e7808093bab13 to your computer and use it in GitHub Desktop.
<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