您好,欢迎访问一九零五行业门户网

vue如何利用js等比压缩图片

这篇文章介绍的内容是关于vue如何利用js等比压缩图片,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下最近做一个旅游项目 大家都知道旅游项目图片居多
    1.在项目中由于图片尺寸过大  再加上给图片设置了宽高导致图片压缩严重
*下面我给大家看一下原图
2. 设置图片的方式有很多种  可以通过背景图来设置background;在项目中一些小图片建议使用字体图标代替?
3.下面给大家展示设置宽高的图片
033cf22c79fbcb18f17f4543fe9924ef
         已经远远看到图片已经变形了
4. 在网上看了一些资料结合自己需要的效果 实现了一下
            虽然还是有些误差  但是只要后台设置上传图片规格  对我们压缩图片的效果有很大好处
最后附上代码  (有更好的方法请一起交流)
<template> <p class="hello"> <p class="dom_width"> <img class="img_block" v-for="(item, index) in listimg" :key="index" :src="item" alt=""> </p> </p> </template> <script> export default { name: "helloworld", data() { return { listimg: [ "https://desk-fd.zol-img.com.cn/t_s720x360c5/g5/m00/0d/06/chmkjlojp_qiturjaauxrjdcgieaaiwqaku7i0ac7he992.jpg", "https://desk-fd.zol-img.com.cn/t_s720x360c5/g5/m00/03/00/chmkj1pcn7oiulojaawuofbovoeaakg3anbku8abzrq309.jpg", "https://ss1.bdstatic.com/70cfuxsh_q1ynxgkpowk1hf6hhy/it/u=1046983545,2051560208&fm=27&gp=0.jpg" ] } }, created() { }, mounted() { // 获取所有的img标签 let imglist = document.queryselectorall(".img_block"); // 获取父元素宽高 let parentwh = imglist[0].parentnode; let wid = this.getwidhei(parentwh, 'width'); let hei = this.getwidhei(parentwh, 'height'); // 等比压缩图片 this.autosize(imglist, wid, hei); }, methods: { autosize(listimg, maxwidth, maxheight) { //原图片原始地址(用于获取原图片的真实宽高,当<img>标签指定了宽、高时不受影响) let image = new image(); for (let i = 0; i < listimg.length; i++) { // 获取每一个图片的宽高 image.src = listimg[i].src; // 当图片比图片框小时不做任何改变 if (image.width < maxwidth && image.height < maxheight) { //原图片宽高比例 大于 图片框宽高比例 listimg[i].width = image.width; listimg[i].height = image.height; } else { //原图片宽高比例 大于 图片框宽高比例,则以框的宽为标准缩放,反之以框的高为标准缩放 if (maxwidth / maxheight <= image.width / image.height) { listimg[i].width = maxwidth; //以框的宽度为标准 listimg[i].height = maxwidth * (image.height / image.width); } else { listimg[i].width = maxheight * (image.width / image.height); listimg[i].height = maxheight; //以框的高度为标准 } } } }, // 考虑 ie 的兼容性 getstyle(el) { if (window.getcomputedstyle) { return window.getcomputedstyle(el, null); } else { return el.currentstyle; } }, // 通过当前元素获取宽高 getwidhei(el, name) { let val = name === "width" ? el.offsetwidth : el.offsetheight, which = name === "width" ? ["left", "right"] : ["top", "bottom"]; // display is none if (val === 0) { return 0; } let style = this.getstyle(el); // 左右或上下两边的都减去 for (let i = 0, a; (a = which[i++]); ) { val -= parsefloat(style["border" + a + "width"]) || 0; val -= parsefloat(style["padding" + a]) || 0; } return val; } } }; </script> <!-- add "scoped" attribute to limit css to this component only --> <style scoped> .dom_width { width: 200px; height: 300px; background-color: skyblue; } </style>
相关推荐:
java指定宽度等比例压缩图片
使用html5实现图片的压缩
css图片剪裁与原比例压缩或放大
php图片等比例压缩
以上就是vue如何利用js等比压缩图片的详细内容。
其它类似信息

推荐信息