前端使用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 小时前
深入理解JavaScript 的原型继承
java·开发语言·javascript·原型模式
问道飞鱼2 小时前
Java基础-单例模式的实现
java·开发语言·单例模式
学习使我快乐012 小时前
JS进阶 3——深入面向对象、原型
开发语言·前端·javascript
bobostudio19952 小时前
TypeScript 设计模式之【策略模式】
前端·javascript·设计模式·typescript·策略模式
通信仿真实验室3 小时前
(10)MATLAB莱斯(Rician)衰落信道仿真1
开发语言·matlab
勿语&3 小时前
Element-UI Plus 暗黑主题切换及自定义主题色
开发语言·javascript·ui
黄尚圈圈3 小时前
Vue 中引入 ECharts 的详细步骤与示例
前端·vue.js·echarts
浮华似水4 小时前
简洁之道 - React Hook Form
前端
正小安6 小时前
如何在微信小程序中实现分包加载和预下载
前端·微信小程序·小程序
吾爱星辰6 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin