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

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

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

//结构层,使用动态属性配合计算属性来实现动态样式
 <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背景图图片的缩放。

 <!-- 通过背景图方式展示图片 -->
   <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})`
        };
      };
    },

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值