前端使用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})`
        };
      };
    },
相关推荐
期待のcode7 分钟前
@RequestBody的伪表单提交场景
java·前端·vue.js·后端
栀秋66617 分钟前
防抖 vs 节流:从百度搜索到京东电商,看前端性能优化的“节奏哲学”
前端·javascript
一颗烂土豆17 分钟前
vfit.js v2.0.0 发布:精简、语义化与核心重构 🎉
前端·vue.js·响应式设计
有意义19 分钟前
深入防抖与节流:从闭包原理到性能优化实战
前端·javascript·面试
幺零九零零42 分钟前
Golang-Swagger
开发语言·后端·golang
可观测性用观测云1 小时前
网站/接口可用性拨测最佳实践
前端
2503_928411561 小时前
12.26 小程序问题和解决
前端·javascript·微信小程序·小程序
灼华_1 小时前
超详细 Vue CLI 移动端预览插件实战:支持本地/TPGZ/NPM/Git 多场景使用(小白零基础入门)
前端
借个火er1 小时前
npm/yarn/pnpm 原理与选型指南
前端
总之就是非常可爱1 小时前
vue3 KeepAlive 核心原理和渲染更新流程
前端·vue.js·面试