【快应用】图片放大预览功能的实现

 【关键词】

放大、image、background-position

 

【问题背景】

快应用中并没有直接的放大图片预览的功能,然而是可以利用现有的功能去实现图片的放大预览功能的。这样在快应用中浏览页面内容遇到图片时,遇到一些小图,觉得图片内容是不错的,就可以点击图片局部地方,放大查看图片的部分细节,提升用户体验。

 

【解决方案】

实现上主要分为两部分:

一、获取要展示的局部图片;

这个是比较好实现的,我们只要实时获取在图片上滑动时的一个X,Y坐标,这个可以用touchmove事件返回的offsetX和offsetY来获取。

cke_2568.png​​

move(e) {

      this.display = true

      if (e.changedTouches[0].offsetX < 500 && e.changedTouches[0].offsetX > 0) {

        this.positionX = 0 - e.changedTouches[0].offsetX;

      }

      if (e.changedTouches[0].offsetY < 500 && e.changedTouches[0].offsetY > 0) {

        this.positionY = 0 - e.changedTouches[0].offsetY;

      }

    },

二、显示放大的局部图片;

这里是使用一个div块 + background的各个属性来实现的。

background-image:用来展示图片(一张原图);

background-size:设置背景图大小来选择放大的倍数;image大小是500*500,该值设置的1000*1000,即图片被放大了4倍。

background-position:设置背景图展示的位置属性,即展示局部放大后的图片;此处是动态填入处理后的touchmove事件返回的XY坐标,需要将值取反,如下所示:

this.positionX = 0 - e.changedTouches[0].offsetX;

this.positionY = 0 - e.changedTouches[0].offsetY;

细节部分:滑动超过图片的范围时,就显示对应的四个角的位置。

实现代码:

<template>

  <!-- Only one root node is allowed in template. -->

  <div class="container">

    <text class="title">图片放大预览功能,点击图片后,在图片上滑动</text>

    <div>

      <image id="imgid" class="img" src="/Common/logo.png" ontouchmove="move" ontouchend="moveEnd"></image>

    </div>

    <div class="preview" show="{{display}}" style="background-position: {{positionX}} {{positionY}};"></div>

  </div>

</template>

 

<style>

  .container {

    flex-direction: column;

    align-items: center;

  }

 

  .title {

    font-size: 50px;

  }

  .img {

    width: 500px;

    height: 500px;

  }

  .preview {

    width: 500px;

    height: 500px;

    background-image: url(/Common/logo.png);

    background-size: 1000px 1000px;

    margin-top: 10px;

  }

</style>

 

<script>

  module.exports = {

    data: {

      display: false,

      positionX: 0,

      positionY: 0,

    },

    onInit() {

      this.$page.setTitleBar({

        text: '图片预览',

        textColor: '#ffffff',

        backgroundColor: '#007DFF',

        backgroundOpacity: 0.5,

        menu: true

      });

    },

    move(e) {

      this.display = true

      if (e.changedTouches[0].offsetX < 500 && e.changedTouches[0].offsetX > 0) {

        this.positionX = 0 - e.changedTouches[0].offsetX;

      }

      if (e.changedTouches[0].offsetY < 500 && e.changedTouches[0].offsetY > 0) {

        this.positionY = 0 - e.changedTouches[0].offsetY;

      }

    },

    moveEnd() {

      this.display = false

    }

  }

</script>
posted @ 2023-08-18 10:10  Mayism123  阅读(25)  评论(0编辑  收藏  举报