Cropperjs is a very powerful and simple image cropping tool, it can be configured very flexible, support mobile, including Internet Explorer 9 and other modern browsers. (The key is that it’s easy to use in a few lines of code.)
Practical renderings
You can also preview the clipping area. After confirming the clipping, a Canvas object containing the clipping picture can be generated. With the help of Canvas toDataURL method, a Base64 image can be generated. There is another way that does not use canvas. The rich API of this tool can be used to get the data of the clipped area relative to the original image, and then the clipped image can be displayed by using the data to perform the absolute positioning of CSS. This way can ensure that the image is not distorted and complete.
Practice key code
Vue framework to do a small demo, the use of the method is very simple, the key is to understand the tool rich capabilities, and know when to use it.
<template>
<div class="hello">
<p>preview</p>
<div class="before"></div>
<iy-button style="margin: 30px auto;" type="error" @click="sureSava">tailoring</iy-button>
<div class="container">
<div class="img-container">
<img src=".. /assets/test.jpg" ref="image" alt="">
</div>
<div class="afterCropper">
<img :src="afterImg" alt="">
</div>
</div>
</div>
</template>
<script>
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
export default {
name: 'HelloWorld',
data () {
return {
myCropper: null.afterImg: ' '}},mounted() {
this.init()
},
methods: {
init(){
this.myCropper = new Cropper(this.$refs.image, {
viewMode: 1.dragMode: 'none'.initialAspectRatio: 1.aspectRatio: 1.preview: '.before'.background: false.autoCropArea: 0.6.zoomOnWheel: false,}}),sureSava(){
this.afterImg = this.myCropper.getCroppedCanvas({
imageSmoothingQuality: 'high'
}).toDataURL('image/jpeg')}}}</script>
<! -- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.container{
display: flex;
}
.before{
width: 100px;
height: 100px;
overflow: hidden;
/* This property can get the desired effect */
}
.img-container{
height: 400px;
overflow: hidden;
}
.afterCropper{
flex: 1;
margin-left: 20px;
border: 1px solid salmon;
text-align: center;
}
.afterCropper img{
width: 150px;
margin-top: 30px;
}
</style>
Copy the code
Since the translation of documents
Official Github documentation: github.com/fengyuanche…
The official document is easy to understand, and I translated it simply according to my understanding. If you are too lazy to translate, please refer to it for reference. There may be some inaccuracies, please judge by yourself, especially the distinction between the concepts of container, Canvas, image and crop box. There are a few things that might be wrong, but let’s look at this picture to understand:
Here is the document (IE9+)
Using cropperjs
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
this.myCropper = new Cropper('Clipped object'.'Configuration Object') // Return a cropper object
this.myCropper.getCroppedCanvas().toDataURL('image/jpeg') // Get the cropped base64 image
this.myCropper.getCropBoxData(); // Get clipping box data
this.myCropper.setCropBoxData(); // Set clipping box data
this.myCropper.getCanvasData(); // Get image data
this.myCropper.setCanvasData(); // Set the image data
Copy the code
A configuration object
Github.com/fengyuanche…
Note: The first value is the default value
viewMode
View control- 0 unlimited
- 1 Restrict cropping boxes to not go beyond the scope of the picture
- 2 Limit the clipping box to not exceed the scope of the image and the image fill mode to cover the longest edge fill
- 3 limit the clipping box can not exceed the scope of the picture and the picture filling mode is the shortest contain
dragMode
Drag and drop image mode- Crop forms a new clipping box
- Move The picture can be moved
- None
initialAspectRatio
The initial value of the clipping box aspectRatio is the same as the image aspectRatio by default. This value is available only when aspectRatio is not setaspectRatio
Set the clipping box to a fixed aspect ratiodata
Previously stored clipped data is automatically set at initialization and is only available if autoCrop is set to truepreview
Preview Sets a region container to preview the clipped result- Element, Array (elements), NodeList or String (selector)
responsive
Reactive rerendering after window sizing defaults to Truerestore
Restores clipped areas after window sizing defaults to TruecheckCrossOrigin
The default is true if the copied image element is crossOrigin and a timestamp is added to SRC to avoid loading errors due to browser caching when reloading imagescheckOrientation
Check image orientation information (only for JPEG images) Default true Does some processing to the image orientation value when rotating the image to solve some problems on IOS devicesmodal
Whether to show black mask between picture and cropping box Defaults to trueguides
Whether to show the dotted line of clipped boxes defaults to truecenter
Whether to show the ‘+’ indicator in the middle of the clipping box Defaults to truehighlight
Whether to show the white mask above the cropping box (very light) Defaults to truebackground
Whether to display a gridded background in the container defaults to trueautoCrop
Allows automatic cropping of images with data at initialization using the default trueautoCropArea
Set the clipping area to the size of the image from 0 to 1. By default, 0.8 represents 80% of the areamovable
Whether images can be moved defaults to truerotatable
Whether images can be rotated defaults to truescalable
Whether the image can be zoomed (width can be changed) defaults to truezoomable
Whether the image can be zoomed (changing the focal length) defaults to truezoomOnTouch
Whether the picture can be zoomed by dragging and touching defaults to truezoomOnWheel
Whether pictures can be zoomed by mouse wheel Defaults to truewheelZoomRatio
Set the mouse wheel zoom sensitivity to 0.1 by defaultcropBoxMovable
Whether clipping boxes can be dragged defaults to TruecropBoxResizable
Whether the clipping box size can be changed default truetoggleDragModeOnDblclick
Can move and crop modes be toggled by double-clicking? Default true Cannot be toggled when the move mode is None. This setting must be supported by the browserMinContainerWidth (200), minContainerHeight (100), minCanvasWidth (0), minCanvasHeight (0), minCropBoxWidth (0), minCropBoxHeight ( 0)
The default values are in parentheses. Note that the minimum width and width of the clipping box are relative to the page, not the image
methods
Note: If the method is not set to return any value, it returns an instance of Cropper so multiple methods can be chained
crop()
Display clipping box manuallyreset()
Reset the picture and crop box to their initial statereplace(url[, hasSameSize])
Replace the image path and rebuild the cropping box- The new url path
- HasSameSize Default value is false. If this parameter is set to true, the new and old images have the same size. You only need to change the path without rebuilding the cropping frame
enable()
Defrost cropping boxdisable()
Freezing clipping boxdestroy()
Destroy the clipping box and remove the Cropper instancemove(offsetX[, offsetY])
Moving picture specifies the distance a parameter represents the horizontal and vertical moving distance the samemoveTo(x[, y])
To move the picture to a specified point, a parameter represents the same distance as the horizontal or vertical movementzoom(ratio)
Scaling ratio greater than zero means scaling up less than scaling downzoomTo(ratio[, pivot])
Scale and set the center point positionrotate(degree)
Rotation is like CSSrotateTo(degree)
Rotate to an absolute AngleScale (scaleX[, scaleY]), scaleX(scaleX), scaleY(scaleY)
Scaling a parameter represents the horizontal and vertical scaling values as wellgetData([rounded])
Return clipped area based on the original image! The original size! If rounded data is displayed, it can be displayed directly on the original screen. Rounded data is rounded by defaultsetData(data)
Changing the clipping area based on the position and size of the original image only works if viewMode is not 0GetContainerData (), getImageData(), getCanvasData(), setCanvasData(data), getCropBoxData(), setCropBoxData(data)
Container, picture container (canvas), picture, clipping area relative to the container data set and obtaingetCroppedCanvas([options])
Gets a Canvas object for the cropped image. Options sets some data for this canvas- Width, height, minWidth, minHeight, maxWidth, maxHeight, fillColor, imageSmoothingEnabled (whether the image is smooth Default true), imageSmoothingQuality (default low, medium, high)
setAspectRatio(aspectRatio)
Change the aspect ratio of the clipping areasetDragMode([mode])
Set drag and drop image mode
The event
ready
The preparation event before rendering (the image is loaded and the Cropper instance is ready)Crop start, cropmove, cropend, crop
Start drawing cutting frame (or canvas), cut out of the box (or canvas) midway, cutting box (or canvas) by cutting finished, event event. Detail. OriginalEvent, event. The detail. The action- When autoCrop is true, the crop event is emitted before Ready
zoom
Clipping the box zoom event