1. 程式人生 > >vue中使用js等比壓縮圖片

vue中使用js等比壓縮圖片

最近做一個旅遊專案 大家都知道旅遊專案圖片居多

    1.在專案中由於圖片尺寸過大  再加上給圖片設定了寬高導致圖片壓縮嚴重

        *下面我給大家看一下原圖

        

    2. 設定圖片的方式有很多種  可以通過背景圖來設定background;在專案中一些小圖片建議使用字型圖示代替?

    3.下面給大家展示設定寬高的圖片

                                        <img width="200" height="300" src="https://desk-fd.zol-img.com.cn/t_s720x360c5/g5/M00/0D/06/ChMkJlojp_qITurJAAuxrJdcGiEAAiwQAKU7i0AC7HE992.jpg" alt="">

         已經遠遠看到圖片已經變形了

  4. 在網上看了一些資料結合自己需要的效果 實現了一下

            雖然還是有些誤差  但是隻要後臺設定上傳圖片規格  對我們壓縮圖片的效果有很大好處

            

            最後附上程式碼  (有更好的方法請一起交流)

<template> <div class="hello"> <div class="dom_width"> <img class="img_block" v-for="(item, index) in listImg" :key="index" :src
="item" alt=""> </div> </div></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>