前端使用scale属性结合CSS动态样式实现动态的图片缩放效果

废话不多说,直接上代码:

示例一,使用css动态样式结合scale进行src图片的缩放。

javascript 复制代码
//结构层,使用动态属性配合计算属性来实现动态样式
 <img  :src="selectedItem.url" alt="" :style="elementStyle(item)" >
//在计算属性中,使用return(item)来接收从结构层中传递的相关宽高值
computed: {
    elementStyle() {
      return (item) => {
        //注意此处1038以及518是设定的父容器的盒子大小                                                    
        const scale_x = 1038 / this.selectedItem.width;                                              
        const scale_y = 518 / this.selectedItem.height;
        const scale = scale_x < scale_y ? scale_x : scale_y;
        const rect_width = scale * this.selectedItem.width;
        const rect_height = scale * this.selectedItem.height;
        // const background_size_x = scale * this.selectedItem.width;
        // const background_size_y = scale * this.selectedItem.height;
        // const background_position_x = scale * this.selectedItem.width;
        // const background_position_y = scale * this.selectedItem.height;

        return {
          // backgroundSize: `${background_size_x}px ${background_size_y}px`,
          // backgroundPosition: `${background_position_x}px ${background_position_y}px`,
          width: `${rect_width}px`,
          height: `${rect_height}px`
        };
      }
    }
  },

示例二,使用css动态样式结合scale进行background背景图图片的缩放。

javascript 复制代码
 <!-- 通过背景图方式展示图片 -->
   <div :style=getelementStyle(item)></div>
//在计算属性中
 getelementStyle() {
      return (item) => {
     //注意此处188以及108是设定的父容器的盒子大小     
        const scale_x = 188 / item.width;
        const scale_y = 108 / item.height;
        const scale = scale_x < scale_y ? scale_x : scale_y;
        const rect_width = scale * item.width;
        const rect_height = scale * item.height;
        const background_size_x = scale * item.width;//此处width为整张背景图的宽度
        const background_size_y = scale * item.height;//此处height为整张背景图的高度
        const background_position_x = scale * item.x;//x为已知坐标值
        const background_position_y = scale * item.y;//y为已知坐标值

        return {
          backgroundSize: `${background_size_x}px ${background_size_y}px`,
          backgroundPosition: `${background_position_x}px ${background_position_y}px`,
          width: `${rect_width}px`,
          height: `${rect_height}px`,
          backgroundImage: `url(${item.url})`
        };
      };
    },
相关推荐
坐吃山猪2 分钟前
Python之PDF小工具
开发语言·python·pdf
小肥宅仙女2 分钟前
React + ECharts 多图表联动实战:从零实现 Tooltip 同步与锁定功能
前端·react.js·echarts
代码栈上的思考3 分钟前
MyBatis——动态SQL讲解
java·开发语言·数据库
如果你好3 分钟前
一文了解 Cookie、localStorage、sessionStorage的区别与实战案例
前端·javascript
鹏北海3 分钟前
Vue3 + Axios 企业级请求封装实战:从零搭建完整的 HTTP 请求层
前端·vue.js·axios
前端无涯4 分钟前
React父子组件回调传参避坑指南:从基础到进阶实践
前端·react.js
RichardMiao4 分钟前
axios 的 withCredentials 到底做了什么?
前端·javascript·http
donecoding5 分钟前
CSS scroll-behavior 与 JS scrollTo 的协同与博弈
前端
王柏龙7 分钟前
c# aggregate使用
开发语言·c#
小鸡吃米…7 分钟前
Python - 构造函数
开发语言·python