Cropper.js是一款很好用的图片裁剪工具,能够对图片的尺寸、宽高比进行裁剪,知足诸如裁剪头像上传、商品图片编辑之类的需求。javascript
github: https://github.com/fengyuanchen/cropperjscss
网站: https://fengyuanchen.github.io/cropperjs/vue
使用很简单,首先须要一个image或者canvas元素:java
<!-- Wrap the image or canvas element with a block element (container) --> <div> <img id="image" src="picture.jpg"> </div>
/* Limit image width to avoid overflow the container */ img { max-width: 100%; /* This rule is very important, please do not ignore this! */ }
而后使用此元素建立Cropper:git
// import 'cropperjs/dist/cropper.css'; import Cropper from 'cropperjs'; const image = document.getElementById('image'); const cropper = new Cropper(image, { aspectRatio: 16 / 9, crop(event) { console.log(event.detail.x); console.log(event.detail.y); console.log(event.detail.width); console.log(event.detail.height); console.log(event.detail.rotate); console.log(event.detail.scaleX); console.log(event.detail.scaleY); }, });
vue代码:github
<template> <div> <div style="width: 750px; height: 500px; margin: 20px; border: dashed #cacaca 1px; text-align: center;"> <img :src="cropperImg" style="max-width: 100%" ref="img"> </div> </div> </template> <script> import Cropper from 'cropperjs' // import 'cropperjs/dist/cropper.min.css' export default { name: "ImgCropper", data () { return { cropperImg: '', cropper: '', imgName: '' } }, mounted () { this.initCropper() }, methods: { initCropper () { let cropper = new Cropper(this.$refs.img, { viewMode: 1, aspectRatio: 16/9, }) this.cropper = cropper }, } } </script>
由于img元素的src属性为空,裁剪区域显示空白。通常的需求是上传图片裁剪,添加上传图片功能:ajax
<input type="file" @change="uploadImg" />
uploadImg (event) { const img = event.target.files[0] this.cropperImg = URL.createObjectURL(img) this.imgName = img.name },
点击上传图片后就能够裁剪了:canvas
将裁剪的图片保存或者上传:跨域
uploadCropImg () { const _this = this this.cropper.getCroppedCanvas().toBlob(async function(blob) { const params = new FormData() params.append('upload_file', blob, _this.imgName) $.ajax(...) }, 'image/jpeg') },
canvas转换为Blob时注意第二个参数默认是image/png的,接口上传有大小限制的状况下,能够设置为image/jpeg。缓存
保存图片:
saveCropImg () { const _this = this this.cropper.getCroppedCanvas().toBlob(function(blob) { const href = window.URL.createObjectURL(blob); const downloadElement = document.createElement('a'); downloadElement.href = href; downloadElement.download = _this.imgName document.body.appendChild(downloadElement); downloadElement.click(); document.body.removeChild(downloadElement); window.URL.revokeObjectURL(href); }, 'image/jpeg') },
这样简单的上传、裁剪、保存功能就实现了。
Cropper还有不少有用的选项,比较重要的:
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。
Number,croper box的宽高比,能够为裁剪设置固定的宽高比,值为NaN时,可自由裁剪。能够使用Shift键来切换或者固定宽高比。
Object,能够用来预设crop box,初始化的时候提供给SetData()使用。
Boolean,默认值true。检查图片是否跨域,图片跨域时会为图片添加crossOrigin属性,并为图片地址添加一个随机时间戳避免缓存。
<img crossorigin="anonymous" src="https://fengyuanchen.github.io/cropperjs/images/picture.jpg?timestamp=1547879277777" class="cropper-hide" style="width: 752px; height: 423px; transform: none;">
显示crop box
new Cropper(image, { autoCrop: false, ready() { // Do something here // ... // And then this.cropper.crop(); }, });
将crop box置于初始的状态,宽高比,大小等。
清除crop box
destroy Cropper实例。
替换img的url地址。
移动canvas
放大或者缩小canvas
旋转image
改变image的宽高比,拉伸等。
获取,设置croper box的实际位置,大小数据
获取container的大小数据
获取image的位置,大小等相关信息。
获取canvas的位置,大小信息。
获取crop box的位置,大小信息等,与getData()的区别是,getData()是获取的实际大小,getCropBoxData()获取的是显示大小,由于image通常是缩小显示的。
比较重要的方法,获取一个HTMLCanvasElement元素,绘制了整个crop box。
能够在options中设置宽高,也能够取默认值:
cropper.getCroppedCanvas({ width: 160, height: 90, minWidth: 256, minHeight: 256, maxWidth: 4096, maxHeight: 4096, fillColor: '#fff', imageSmoothingEnabled: false, imageSmoothingQuality: 'high', });
转为Blob:
// Upload cropped image to server if the browser supports `HTMLCanvasElement.toBlob` cropper.getCroppedCanvas().toBlob((blob) => { const formData = new FormData(); formData.append('croppedImage', blob); // Use `jQuery.ajax` method $.ajax('/path/to/upload', { method: "POST", data: formData, processData: false, contentType: false, success() { console.log('Upload success'); }, error() { console.log('Upload error'); }, }); });
转为base64 url:
cropper.getCroppedCanvas().toDataURL('image/png')
若是手机上不支持toBlob(),有个polyfill JavaScript-Canvas-to-Blob 。
设置crop box的宽高比。
Cropper实例是挂在img上的,能够为目标img添加事件
img已加载好,Cropper实例能够被操做了:
let cropper; image.addEventListener('ready', function () { console.log(this.cropper === cropper); // > true }); cropper = new Cropper(image);
开始裁剪
裁剪时事件
裁剪结束事件
crop box发生变化时的事件。
这些事件均可以放在Cropper的options之中。
好比,限定裁剪时的宽高比:
initCropper () { let cropper = new Cropper(this.$refs.img, { viewMode: 1, cropmove () { const cropper = this.cropper; const minAspectRatio = 0.5 const maxAspectRatio = 1.5 const cropBoxData = cropper.getCropBoxData(); const aspectRatio = cropBoxData.width / cropBoxData.height; if (aspectRatio < minAspectRatio) { cropper.setCropBoxData({ width: cropBoxData.height * minAspectRatio }); } else if (aspectRatio > maxAspectRatio) { cropper.setCropBoxData({ width: cropBoxData.height * maxAspectRatio }); } } }) this.cropper = cropper },