The official documentation
The basic use
1. Install CropperJS
npm install cropperjs
Copy the code
2. Introduce CSS and JS
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
Copy the code
3. Initialize the vm in Mounted
const image = this.$refs.img 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) } }) console.log(cropper)Copy the code
4. Configure CropperJS
const cropper = new Cropper(image, {
viewMode: 1.// Can only move within the clipped image range
dragMode: 'move'.// Both canvas and image can be moved
aspectRatio: 1.// Clipping area default square
autoCropArea: 1.// Automatically adjust cropping images
cropBoxMovable: false.// Forbid clipping area to move
cropBoxResizable: false.// Disable clipping area scaling
background: false // Turn off the default background
})
Copy the code
The specific application
-
Introduce the JS file and style file for CropperJS
-
Get the IMG tag in mouted
-
Configure the parameters of Cropperjs
-
Register onConfirm for the Finish button
<template>
<div class="update-avatar">
<img :src="img" ref="imgRef" />
<div class="toolbar">
<span @click="$emit('close')">cancel</span>// 4. Register the click event for the finish button<span @click="onConfirm">complete</span>
</div>
</div>
</template>
<script>
// 1. Import cropperjs js files and style files
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
props: ['img'].data() {
return {
cropper: ' '}},// created- initializes data --data/ computes property initializations
// mounted- Assembles data and templates into a page
mounted() {
// 2. Get the img tag
const image = this.$refs.imgRef
// 3. Configure cropperjs parameters
this.cropper = new Cropper(image, {
viewMode: 1.// Can only move within the clipped image range
dragMode: 'move'.// Both canvas and image can be moved
aspectRatio: 1.// Clipping area default square
autoCropArea: 1.// Automatically adjust cropping images
cropBoxMovable: false.// Forbid clipping area to move
cropBoxResizable: false.// Disable clipping area scaling
background: false // Turn off the default background}}})</script>
Copy the code
- Click ok in the event to implement cropped image submission
- Create formData and add the current IMG data to it
- Initiate a request to update the image
methods:{
// 5. Click Ok
onConfirm(){
this.cropper.getCroppedCanvas().toBlob(async blob => {
// 5.1 Creating formData
const formData = new FormData()
formData.append('photo', blob)
// 5.2 Initiate a request to update the image
const { data } = await updateUserAvatar(formData)
})
}
}
Copy the code