JSFiddle - React, Tailwind, and code Playground

by cheongjin kim

HTML

<script src="https://unpkg.com/vue@2/dist/vue.js"></script>

<div id="vue-async-image">
	<div v-for="item in list" class="image-wrap">
		<img v-bind:src="resizeImage(item)" v-bind:style="item.style">
	</div>
</div>

CSS

.image-wrap {
	width:80px;
	height:80px;
	border-radius:5px;
	overflow:hidden;
	margin:10px;
}

JavaScript

var vue = new Vue({
	el : '#vue-async-image',
	data : {
		list : [
			{
				url : 'https://dummyimage.com/600x400/0f0/f00.png',
				style : ''
			},
			{
				url : 'https://dummyimage.com/300x300/00f/0f0.png',
				style : ''
			},
			{
				url : 'https://dummyimage.com/200x500/f00/00f.png',
				style : ''
			}
		]
	},
	methods : {
		 resizeImage : function(item) {
		 
		 	var domSize = {
				width: 80,
				height: 80
			};
			
			if(!item.style) {
			
				var image = new Image();
				image.src = item.url;
				image.onload = function() {
					var size = {
						width : this.width,
						height : this.height
					}

					var calculationSize = {
						width : size.width * (domSize.height/this.height),
						height : size.height * (domSize.width/this.width)
					};

					if(size.width >= size.height) {
						item.style = 'height:100%;';

						var marginLeft = (domSize.width/2) - (calculationSize.width/2);
						item.style += 'margin-left:{left}px'.replace('{left}', marginLeft);

					} else {
						item.style = 'width:100%;';
						
						var marginTop = (domSize.height/2) - (calculationSize.height/2);
						item.style += 'margin-top:{top}px'.replace('{top}', marginTop);
					}

				};
			
			}
		
			return item.url;
		}
	}
});