vue对base64图片进行缩放
描述
后台传递来的是base64格式的图片数据,直接显示的话有的图片大小格式不符合要求,所以在前端接收到后台的响应数据后,需要对图片格式进行处理后再显示。
代码
<template>
<div>
<Carousel class="header-boox" v-model="banner" :autoplay-speed="speedS" autoplay loop>
<CarouselItem v-for="(item,index) in imageArray" :value="item" :key="index">
<div class="carousel-item">
<img :src="item"/>
</div>
</CarouselItem>
</Carousel>
</div>
</template>
<script>
export default {
name: 'Home',
components: {},
data(){
return {
banner: 0,
speedS: 5000,
imageArray: [],
}
},
methods: {
queryHome() {
let params = {};
apiRequest(this,queryCarouselMap(params),response => {
response.carouseList.map((item) => {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let imagePath;
let image = new Image();
//为了在方法内部的方法中使用this对象,相当于起别名。
let _this = this;
image.onload = function(e) {
let width = image.width;
if (width>1110){
//如果等比缩放可以计算宽度和长度,我这里不需要等比缩放,所以直接写死
var anw = document.createAttribute("width");
anw.nodeValue = 1110;
var anh = document.createAttribute("height");
anh.nodeValue = 250;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(image,0,0,1110,250);
imagePath = canvas.toDataURL('image/png',1);
}else{
imagePath = item.imagePath;
}
_this.imageArray.push(imagePath);
};
image.src = item.imagePath;
});
});
}
},
created: {
this.queryHome();
}
}
</script>