JAVASCRIPTHbuilder+MUI开发5+appVue小记

vue插件--图片裁剪

2016-10-14  本文已影响8773人  markdown

基础要求

知道如何使用vue-cli
熟悉vue1.0、了解sass
了解html5本地图片裁剪

准备工作

使用vue-cli安装vue1.0 webpack框架
安装node-sass、sass-loader

插件编写

图片裁剪流程为:

  1. 读取图片
  2. 显示裁剪页面
  3. 手动缩放移动图片
  4. 确认裁剪,返回图片数据,隐藏裁剪页面

编写图片裁剪插件我们首先确定裁剪页面元素和样式,然后编写读取图片和显示页面的方法,进入裁剪页面后,对用户手势进行处理完成图片裁剪移动功能,最后返回裁剪后的图片数据并隐藏裁剪页面。

编写裁剪页面

读取图片必然需要input[type="file"]元素,裁剪图片需要显示图片所以需要img元素,要确定裁剪内容的范围,需要一个div元素,这些是必要的元素,为了显示效果不要太难看还添加其他元素:

<template>
  <div class="cropper-page" v-show="isShow" v-el:cropper-page>
    <header-bar v-el:header>
      <span slot="right" @click="confirm">确定</span>
    </header-bar>
    <img src="" alt="" class="cropper-img" :style="imageStyle" v-el:img>
    <div class="cover" :style="{height: coverHeight + 'px'}"></div>
    <div class="cropper-box" @touchstart.prevent="touchStart" @touchmove.prevent="touchMove" @touchend.prevent="touchEnd" v-el:crop-box></div>
    <div class="cover" :style="{height: coverHeight + 'px'}">
      {{info}}
    </div>
  </div>
  <input v-el:file type="file" accept="image/*" @change="readImage">
</template>
<style lang="css" scoped>
  .cropper-page{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 2;
    background-color: #fff;
    overflow: hidden;
  }
  .cover{
    background-color: rgba(0,0,0,0.2);
  }
  .cropper-img{
    position: absolute;
    z-index: -1;
  }
  input[type="file"]{
    opacity: 0;
    position: fixed;
    top: -1000px;
    left: -1000px;
  }
</style>

为了让裁剪窗口出现在合适的位置,方便获取元素位置信息,关于位置的样式我通过js进行实现:

    initCropper () {
      this.isShow = true // 显示裁剪界面
      // 回调会在dom更新后调用,如果不使用$nextTick,无法获取元素正确的高度
      this.$nextTick(() => {
        let cropperPage = this.$els.cropperPage
        let pageWidth = cropperPage.clientWidth
        let pageHeight = cropperPage.clientHeight
        let headerHeight = this.$els.header.clientHeight
        console.log(cropperPage)
        this.coverHeight = (pageHeight - headerHeight - pageWidth) / 2
        let cropBoxTop = this.coverHeight + headerHeight
        this.imageState.left = 0
        this.imageState.top = 0
        this.imageStyle.top = cropBoxTop + 'px'
        this.$els.cropBox.style = 'height:' + pageWidth + 'px'
        // var cropBoxRect = this.$els.cropBox.getBoundingClientRect() // 获取的元素没有预期的参数
        this.cropBoxRect = {
          left: 0,
          top: cropBoxTop,
          width: pageWidth,
          height: pageWidth
        }

        let img = this.$els.img
        var width = this.imageState.width = img.naturalWidth
        var height = this.imageState.height = img.naturalHeight
        // 计算imageState
        if (width > height) {
          this.minScale = this.imageState.scale = this.cropBoxRect.height / height
          this.imageState.left = (width * this.imageState.scale - this.cropBoxRect.width) / 2
        } else {
          this.minScale = this.imageState.scale = this.cropBoxRect.width / width
          this.imageState.top = (height * this.imageState.scale - this.cropBoxRect.height) / 2
        }
      })

读取图片与显示裁剪页面

用户通过this.$broadcast('showCropper')触发组件事件:

 events: {
    showCropper () {
      this.$els.file.click()
    }
  },

组件触发input[type="file"]元素的click事件,用户选择图片,触发change事件,执行方法readImage,将读取图片赋值给页面img元素,初始化页面后显示:

    readImage (event) {
      console.log('read')
      var file = event.target.files[0]
      console.log(file)
      var reader = new window.FileReader()
      reader.onload = () => {
        // 通过 reader.result 来访问生成的 DataURL
        this.$els.img.src = reader.result
        // 显示页面并初始化页面
        this.initCropper()
      }
      reader.readAsDataURL(file)
    },

实现图片的移动与缩放

要实现图片的移动和缩放,需要监听元素的touch事件(如果希望在pc端实现图片缩放需要监听鼠标滚轮事件),根据touch事件的反馈改变图片样式。
实现图片移动较为简单,记录移动距离,然后使图片移动相同的距离,如果又多个触摸点那么就记录中点的移动距离。
实现图片缩放需要至少两个触摸点,记录两点的距离,随着两点距离的改变,对图片进行缩放,图片原本的大小/图片缩放后大小应该等于两点最初距离/两点最后距离,如果图片移动没有记录多点的话,缩放效果会比较奇怪,一般图片缩放的同时,两点之间的中点也是不断改变的。

    touchStart (event) {
      var fingerCount = event.touches.length
      if (fingerCount) {
        // 记录触摸初始位置
        let touchEvent = event.touches[0]
        this.touchPos = {
          x: touchEvent.pageX,
          y: touchEvent.pageY
        }
      }

      if (fingerCount >= 2) {
        // 获取两点距离、中点位置;两点距离old/new=放大倍数;中点位置,缩放中心;
        let point0 = event.touches[0]
        let point1 = event.touches[1]

        this.distance = getDinstance(point0, point1)
        this.touchPos = this.getFocalPoint(point0, point1)
        // 设置缩放倍数,
      }
    },
    touchMove (event) {
      // 根据触摸点位移,移动图片,重置触摸点位置
      var fingerCount = event.touches.length

      var touchEvent = event.touches[0]

      if (fingerCount === 1) {
        let distX = touchEvent.pageX - this.touchPos.x
        let distY = touchEvent.pageY - this.touchPos.y
        let newX = this.imageState.left - distX
        let newY = this.imageState.top - distY

        let scale = this.imageState.scale
        let maxX = this.imageState.width * scale - this.cropBoxRect.width
        let maxY = this.imageState.height * scale - this.cropBoxRect.height
        this.imageState.left = newX < 0 ? 0 : (newX > maxX ? maxX : newX)
        this.imageState.top = newY < 0 ? 0 : (newY > maxY ? maxY : newY)
        this.touchPos.x = touchEvent.pageX
        this.touchPos.y = touchEvent.pageY
      } else if (fingerCount > 1) {
        let point0 = event.touches[0]
        let point1 = event.touches[1]

        let distance = getDinstance(point0, point1)
        let zoom = distance / this.distance

        let scale = zoom * this.imageState.scale
        let maxX = this.imageState.width * scale - this.cropBoxRect.width
        let maxY = this.imageState.height * scale - this.cropBoxRect.height
        let touchPos = this.getFocalPoint(point0, point1)
        let newX = zoom * (this.imageState.left + touchPos.x) - touchPos.x
        let newY = zoom * ((this.imageState.top - this.imgInitTop) + touchPos.y) - touchPos.y + this.imgInitTop
        // 限制缩放

        // 图片新位置:由中点位置确认;(新位置到中点)/(旧位置到中点)=(new scale)/(old scale)
        // newLeft - touchPos.x = (distance / this.distance) * (oldLetf - touchPos.x)
        // oldLeft = 0 - this.imageState.left
        // oldTop = imgInitTop - this.imageState.top
        this.distance = distance
        if (scale < this.minScale) {
          this.imageState.scale = this.minScale
        } else {
          this.imageState.scale = scale
          this.imageState.left = newX < 0 ? 0 : (newX > maxX ? maxX : newX)
          this.imageState.top = newY < 0 ? 0 : (newY > maxY ? maxY : newY)
        }
        this.touchPos = touchPos
      }
    },
    touchEnd (event) {
      console.log('end')
    }

返回裁剪图片数据

使用canvas对图片进行处理,使用回调函数返回图片数据

    confirm () {
      let imageState = this.imageState
      let cropBoxRect = this.cropBoxRect
      let scale = imageState.scale
      let image = this.$els.img
      let height = cropBoxRect.height
      let width = cropBoxRect.width

      let canvas = document.createElement('canvas')
      canvas.width = cropBoxRect.width
      canvas.height = cropBoxRect.height
      let ctx = canvas.getContext('2d')
      ctx.drawImage(image, imageState.left / scale, imageState.top / scale, width / scale, height / scale, 0, 0, width, height)
      let data = canvas.toDataURL()
      // 调用处理函数
      this.callback(data)
      // 隐藏页面
      this.isShow = false
    },

调用页面中:

<template>
  <div id="app">
    <h1>图像裁剪</h1>
    <button @click="getImage">图像裁剪</button>
    <image-cropper :callback="loadImage"></image-cropper>
    <img src="" alt="" v-el:test>
  </div>
</template>

将裁剪图片数据返回给img元素

loadImage (data) {
    console.log(data)
    this.$els.test.src = data
}

其他

git: https://github.com/x007xyz/vue-image-cropper

上一篇下一篇

猜你喜欢

热点阅读