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

  • viewModeView 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
  • dragModeDrag and drop image mode
    • Crop forms a new clipping box
    • Move The picture can be moved
    • None
  • initialAspectRatioThe 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 set
  • aspectRatioSet the clipping box to a fixed aspect ratio
  • dataPreviously stored clipped data is automatically set at initialization and is only available if autoCrop is set to true
  • previewPreview Sets a region container to preview the clipped result
    • Element, Array (elements), NodeList or String (selector)
  • responsiveReactive rerendering after window sizing defaults to True
  • restoreRestores clipped areas after window sizing defaults to True
  • checkCrossOriginThe 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 images
  • checkOrientationCheck 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 devices
  • modalWhether to show black mask between picture and cropping box Defaults to true
  • guidesWhether to show the dotted line of clipped boxes defaults to true
  • centerWhether to show the ‘+’ indicator in the middle of the clipping box Defaults to true
  • highlightWhether to show the white mask above the cropping box (very light) Defaults to true
  • backgroundWhether to display a gridded background in the container defaults to true
  • autoCropAllows automatic cropping of images with data at initialization using the default true
  • autoCropAreaSet the clipping area to the size of the image from 0 to 1. By default, 0.8 represents 80% of the area
  • movableWhether images can be moved defaults to true
  • rotatableWhether images can be rotated defaults to true
  • scalableWhether the image can be zoomed (width can be changed) defaults to true
  • zoomableWhether the image can be zoomed (changing the focal length) defaults to true
  • zoomOnTouchWhether the picture can be zoomed by dragging and touching defaults to true
  • zoomOnWheelWhether pictures can be zoomed by mouse wheel Defaults to true
  • wheelZoomRatioSet the mouse wheel zoom sensitivity to 0.1 by default
  • cropBoxMovableWhether clipping boxes can be dragged defaults to True
  • cropBoxResizableWhether the clipping box size can be changed default true
  • toggleDragModeOnDblclickCan 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 browser
  • MinContainerWidth (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 manually
  • reset()Reset the picture and crop box to their initial state
  • replace(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 box
  • disable()Freezing clipping box
  • destroy()Destroy the clipping box and remove the Cropper instance
  • move(offsetX[, offsetY])Moving picture specifies the distance a parameter represents the horizontal and vertical moving distance the same
  • moveTo(x[, y])To move the picture to a specified point, a parameter represents the same distance as the horizontal or vertical movement
  • zoom(ratio)Scaling ratio greater than zero means scaling up less than scaling down
  • zoomTo(ratio[, pivot])Scale and set the center point position
  • rotate(degree)Rotation is like CSS
  • rotateTo(degree)Rotate to an absolute Angle
  • Scale (scaleX[, scaleY]), scaleX(scaleX), scaleY(scaleY)Scaling a parameter represents the horizontal and vertical scaling values as well
  • getData([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 default
  • setData(data)Changing the clipping area based on the position and size of the original image only works if viewMode is not 0
  • GetContainerData (), getImageData(), getCanvasData(), setCanvasData(data), getCropBoxData(), setCropBoxData(data)Container, picture container (canvas), picture, clipping area relative to the container data set and obtain
  • getCroppedCanvas([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 area
  • setDragMode([mode])Set drag and drop image mode

The event

  • readyThe preparation event before rendering (the image is loaded and the Cropper instance is ready)
  • Crop start, cropmove, cropend, cropStart 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
  • zoomClipping the box zoom event