经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Vue.js » 查看文章
Vue中使用Cropper.js裁剪图片
来源:cnblogs  作者:再见紫罗兰  时间:2019/1/21 9:39:39  对本文有异议

Cropper.js是一款很好用的图片裁剪工具,可以对图片的尺寸、宽高比进行裁剪,满足诸如裁剪头像上传、商品图片编辑之类的需求。

github: https://github.com/fengyuanchen/cropperjs

网站: https://fengyuanchen.github.io/cropperjs/

简单使用

使用很简单,首先需要一个image或者canvas元素:

  1. <!-- Wrap the image or canvas element with a block element (container) -->
  2. <div>
  3.   <img id="image" src="picture.jpg">
  4. </div>

  

  1. /* Limit image width to avoid overflow the container */
  2. img {
  3.   max-width: 100%; /* This rule is very important, please do not ignore this! */
  4. }

 然后使用此元素创建Cropper:

  1. // import 'cropperjs/dist/cropper.css';
  2. import Cropper from 'cropperjs';
  3.  
  4. const image = document.getElementById('image');
  5. const cropper = new Cropper(image, {
  6.   aspectRatio: 16 / 9,
  7.   crop(event) {
  8.     console.log(event.detail.x);
  9.     console.log(event.detail.y);
  10.     console.log(event.detail.width);
  11.     console.log(event.detail.height);
  12.     console.log(event.detail.rotate);
  13.     console.log(event.detail.scaleX);
  14.     console.log(event.detail.scaleY);
  15.   },
  16. });

 vue代码:

  1. <template>
  2.   <div>
  3.     <div style="width: 750px; height: 500px; margin: 20px; border: dashed #cacaca 1px; text-align: center;">
  4.       <img :src="cropperImg" style="max-width: 100%" ref="img">
  5.     </div>
  6.   </div>
  7. </template>
  8.  
  9. <script>
  10. import Cropper from 'cropperjs'
  11. // import 'cropperjs/dist/cropper.min.css'
  12.  
  13. export default {
  14.   name: "ImgCropper",
  15.   data () {
  16.     return {
  17.       cropperImg: '',
  18.       cropper: '',
  19.       imgName: ''
  20.     }
  21.   },
  22.   mounted () {
  23.     this.initCropper()
  24.   },
  25.   methods: {
  26.     initCropper () {
  27.       let cropper = new Cropper(this.$refs.img, {
  28.         viewMode: 1,
  29.         aspectRatio: 16/9,
  30.       })
  31.       this.cropper = cropper
  32.     },
  33.   }
  34. }
  35. </script>

 因为img元素的src属性为空,裁剪区域显示空白。一般的需求是上传图片裁剪,添加上传图片功能:

  1. <input type="file" @change="uploadImg" />

  

  1. uploadImg (event) {
  2.   const img = event.target.files[0]
  3.   this.cropperImg = URL.createObjectURL(img)
  4. },

 点击上传图片后就可以裁剪了:

 将裁剪的图片保存或者上传:

  1.     uploadCropImg () {
  2.       const _this = this
  3.       this.cropper.getCroppedCanvas().toBlob(async function(blob) {
  4.         const params = new FormData()
  5.         params.append('upload_file', blob, _this.imgName)
  6.         $.ajax(...)
  7.       }, 'image/jpeg')
  8.     },

 canvas转换为Blob时注意第二个参数默认是image/png的,接口上传有大小限制的情况下,可以设置为image/jpeg。

   保存图片:

  1.     saveCropImg () {
  2.       const _this = this
  3.       this.cropper.getCroppedCanvas().toBlob(function(blob) {
  4.         const href = window.URL.createObjectURL(blob);
  5.       const downloadElement = document.createElement('a');
  6.       downloadElement.href = href;
  7.       downloadElement.download = _this.imgName
  8.       document.body.appendChild(downloadElement);
  9.       downloadElement.click(); 
  10.       document.body.removeChild(downloadElement);
  11.       window.URL.revokeObjectURL(href);
  12.       }, 'image/jpeg')
  13.     },

 这样简单的上传、裁剪、保存功能就实现了。

Options

Cropper还有很多有用的选项,比较重要的:

viewMode

Number,默认值0,可选值0,1,2,3

Cropper容器基本有4个部分,官网示例:

mode为0的情况下,crop box部分可以超出canvans的范围,mode为1,2,3时crop box被限制在canvas范围之内,mode为2,3时会将canvas限制在container之内。

image与crop box都是可以移动的,双击可以切换move mode与crop mode。

aspectRatio

Number,croper box的宽高比,可以为裁剪设置固定的宽高比,值为NaN时,可自由裁剪。可以使用Shift键来切换或者固定宽高比。

data

Object,可以用来预设crop box,初始化的时候提供给SetData()使用。

checkCrossOrigin

Boolean,默认值true。检查图片是否跨域,图片跨域时会为图片添加crossOrigin属性,并为图片地址添加一个随机时间戳避免缓存。

  1. <img crossorigin="anonymous" src="https://fengyuanchen.github.io/cropperjs/images/picture.jpg?timestamp=1547879277777" class="cropper-hide" style="width: 752px; height: 423px; transform: none;">

Methods

crop()

显示crop box

  1. new Cropper(image, {
  2.   autoCrop: false,
  3.   ready() {
  4.     // Do something here
  5.     // ...
  6.  
  7.     // And then
  8.     this.cropper.crop();
  9.   },
  10. });

reset()

将crop box置于初始的状态,宽高比,大小等。

clear()

清除crop box

destroy()

destroy Cropper实例。

replace(url[, hasSameSize])

替换img的url地址。

move(offsetX[, offsetY]),moveTo(x[, y])

移动canvas

zoom(ratio),zoomTo(ratio[, pivot])

放大或者缩小canvas

rotate(degree),rotateTo(degree)

旋转image

scale(scaleX[, scaleY]),scaleX(scaleX),scaleY(scaleY)

改变image的宽高比,拉伸等。

getData([rounded]),setData(data)

获取,设置croper box的实际位置,大小数据

getContainerData()

获取container的大小数据

getImageData()

获取image的位置,大小等相关信息。

getCanvasData(),setCanvasData(data)

获取canvas的位置,大小信息。

getCropBoxData(),setCropBoxData(data)

获取crop box的位置,大小信息等,与getData()的区别是,getData()是获取的实际大小,getCropBoxData()获取的是显示大小,因为image一般是缩小显示的。

getCroppedCanvas([options])

比较重要的方法,获取一个HTMLCanvasElement元素,绘制了整个crop box。

可以在options中设置宽高,也可以取默认值:

  1. cropper.getCroppedCanvas({
  2.   width: 160,
  3.   height: 90,
  4.   minWidth: 256,
  5.   minHeight: 256,
  6.   maxWidth: 4096,
  7.   maxHeight: 4096,
  8.   fillColor: '#fff',
  9.   imageSmoothingEnabled: false,
  10.   imageSmoothingQuality: 'high',
  11. });

 转为Blob:

  1. // Upload cropped image to server if the browser supports `HTMLCanvasElement.toBlob`
  2. cropper.getCroppedCanvas().toBlob((blob) => {
  3.   const formData = new FormData();
  4.  
  5.   formData.append('croppedImage', blob);
  6.  
  7.   // Use `jQuery.ajax` method
  8.   $.ajax('/path/to/upload', {
  9.     method: "POST",
  10.     data: formData,
  11.     processData: false,
  12.     contentType: false,
  13.     success() {
  14.       console.log('Upload success');
  15.     },
  16.     error() {
  17.       console.log('Upload error');
  18.     },
  19.   });
  20. });

 转为base64 url:

  1. cropper.getCroppedCanvas().toDataURL('image/png')

 如果手机上不支持toBlob(),有个polyfill JavaScript-Canvas-to-Blob 。

setAspectRatio(aspectRatio)

设置crop box的宽高比。

Events

Cropper实例是挂在img上的,可以为目标img添加事件

ready

img已加载好,Cropper实例可以被操作了:

  1. let cropper;
  2.  
  3. image.addEventListener('ready', function () {
  4.   console.log(this.cropper === cropper);
  5.   // > true
  6. });
  7.  
  8. cropper = new Cropper(image);

cropstart

开始裁剪

cropmove

裁剪时事件

cropend

裁剪结束事件

crop

crop box发生变化时的事件。

这些事件都可以放在Cropper的options之中。

比如,限定裁剪时的宽高比:

  1.     initCropper () {
  2.       let cropper = new Cropper(this.$refs.img, {
  3.         viewMode: 1,
  4.         cropmove () {
  5.           const cropper = this.cropper;
  6.           const minAspectRatio = 0.5
  7.           const maxAspectRatio = 1.5
  8.           const cropBoxData = cropper.getCropBoxData();
  9.           const aspectRatio = cropBoxData.width / cropBoxData.height;
  10.           if (aspectRatio < minAspectRatio) {
  11.             cropper.setCropBoxData({
  12.               width: cropBoxData.height * minAspectRatio
  13.             });
  14.           } else if (aspectRatio > maxAspectRatio) {
  15.             cropper.setCropBoxData({
  16.               width: cropBoxData.height * maxAspectRatio
  17.             });
  18.           }
  19.         }
  20.       })
  21.       this.cropper = cropper
  22.     },

  

原文链接:http://www.cnblogs.com/linxiyue/p/10288490.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号