前端使用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})`
        };
      };
    },
相关推荐
浩~~24 分钟前
HTML5 浮动(Float)详解
前端·html·html5
为自己_带盐31 分钟前
浅聊一下数据库的索引优化
开发语言·数据库·php
明月看潮生1 小时前
青少年编程与数学 02-019 Rust 编程基础 12课题、所有权系统
开发语言·青少年编程·rust·编程与数学
shengjk11 小时前
序列化和反序列化:从理论到实践的全方位指南
java·大数据·开发语言·人工智能·后端·ai编程
AI大模型顾潇1 小时前
[特殊字符] 本地大模型编程实战(29):用大语言模型LLM查询图数据库NEO4J(2)
前端·数据库·人工智能·语言模型·自然语言处理·prompt·neo4j
passionSnail2 小时前
《用MATLAB玩转游戏开发》推箱子游戏的MATLAB趣味实现
开发语言·游戏·matlab
九月TTS2 小时前
TTS-Web-Vue系列:Vue3实现内嵌iframe文档显示功能
前端·javascript·vue.js
爱编程的小学究2 小时前
【node】如何把包发布到npm上
前端·npm·node.js
Once_day2 小时前
C++之fmt库介绍和使用(1)
开发语言·c++·fmt
我爱加班、、2 小时前
Chrome安装最新vue-devtool插件
javascript·vue.js·chrome·vue-devtool