Crowperjs is a very powerful but simple image cutting tool. It can be configured very flexibly, supports the use of mobile phones, and supports modern browsers including IE9 and above. (the key is that it's easy to use and can be done in a few lines of code.)
Practice effect chart
As shown in the figure, the specified picture can be cropped. You can choose the interactive way of cropping, such as size, aspect ratio, etc. you can preview the cropping area. After confirming the cropping, you can generate a canvas object containing the cropped picture. With the help of the toDataURL method of canvas, you can generate a picture in Base64 format. There is another way of not using canvas. Using the rich api of the tool, you can get the data of the clipping region relative to the original image. Using these data to locate the css absolutely can show the clipped image. This way can ensure that the image is not distorted and complete.
Practice key code
Using the vue framework to make a small demo, the use method is very simple, the key is to understand the rich capabilities of the tool, 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>
Self translation document
Official github documentation: https://github.com/fengyuanchen/cropperjs
The official documents are easy to understand. I have translated them simply according to my understanding. If you are too lazy to translate, you can refer to them. There may be some inaccuracies. Please make your own judgment, especially for the differences between the concepts of container, canvas, image, and crop box. There are several places that may not be right. First look at this picture to understand :
Here are the documents
# cropper - Cut pictures - IE9+ ## Using clipperjs ```javascript import Cropper from 'cropperjs' import 'cropperjs/dist/cropper.css' this.myCropper = new Cropper('Cropped object', 'Configuration objects') //Return to one cropper object this.myCropper.getCroppedCanvas().toDataURL('image/jpeg') //Get the cut base64 Pictures this.myCropper.getCropBoxData(); //Get crop box data this.myCropper.setCropBoxData(); //Set crop box data this.myCropper.getCanvasData(); //Get picture data this.myCropper.setCanvasData(); //Set picture data ``` ## Configuration objects > https://github.com/fengyuanchen/cropperjs __Note: the first value is the default__ - viewMode View control - 0 Unlimited - 1 Limit crop box to pictures - 2 Limit the crop box to be within the range of the picture and the fill mode of the picture is cover Longest edge fill - 3 Limit the crop box to be within the range of the picture and the fill mode of the picture is contain Shortest edge fill - dragMode Drag picture mode - crop Form a new crop box - move Pictures can be moved - none nothing in the world - initialAspectRatio The initial value of the width to height ratio of the crop box is the same as that of the picture by default only when aspectRatio Available without settings - aspectRatio Set the crop box to a fixed aspect ratio - data The previously stored cropped data will be automatically set during initialization only when autoCrop Set to true When available - preview Preview set an area container to preview the cropped result - Element, Array (elements), NodeList or String (selector) - responsive Responsive re rendering after window resizing default true - restore Restore clipped area defaults after window resizing true - checkCrossOrigin Check whether the picture is cross domain default true If it is, attributes will be added to the copied image elements crossOrigin And in src Add a time stamp to avoid loading errors due to browser cache when reloading pictures - checkOrientation Check the orientation information of the picture (only JPEG Picture has) default true When rotating the picture, some processing will be done to the picture direction value to solve the problem IOS Some problems on the equipment - modal Show black mask between picture and crop box default true - guides Show dotted line of crop box default true - center Whether to display the middle of the crop box '+' Indicator default true - highlight Whether to display the white mask (very light) on the crop box by default true - background Whether to display grid like background in the container default true - autoCrop Allow automatic crop picture matching during initialization data Use default true - autoCropArea Set the size of crop area in the picture to 0-1 Default 0.8 Express 80%Region - movable Can I move pictures default true - rotatable Can I rotate pictures default true - scalable Whether the picture can be scaled (length and width can be changed) default true - zoomable Can I zoom the picture (zoom) default true - zoomOnTouch Whether the image can be zoomed by dragging and touching default true - zoomOnWheel Can I zoom pictures by mouse wheel default true - wheelZoomRatio Set the sensitivity of mouse wheel zoom to 0 by default.1 - cropBoxMovable Can I drag the crop box? Default true - cropBoxResizable Can I change the size default of the crop box true - toggleDragModeOnDblclick Can you double-click to switch drag picture mode( move and crop)default true When the drag picture mode is none This setting cannot be switched. The browser must support double click events - minContainerWidth(200),minContainerHeight(100),minCanvasWidth(0),minCanvasHeight(0),minCropBoxWidth(0),minCropBoxHeight(0) The minimum width of the container, picture and clipping box is the default value. Note that the minimum height and width of the clipping box is relative to the page, not relative to the picture ## Method __Note: if the method is not set to return any value, it will return a cropper So multiple methods can use chaining__ - crop() Show crop box manually - reset() Reset picture and crop box to initial state - replace(url[, hasSameSize]) Replace picture path and rebuild crop box - url New path - hasSameSize Default value false Set to true It means that the new and old pictures are the same size, only need to change the path without rebuilding the clipping box - enable() Unfreeze crop box - disable() Freeze crop box - destroy() Destroy crop box and remove cropper Example - move(offsetX[, offsetY]) Moving picture specifies the distance a parameter represents the same horizontal and vertical moving distance - moveTo(x[, y]) Move the picture to a specified point. A parameter represents the same horizontal and vertical moving distance - zoom(ratio) zoom ratio Greater than zero is greater than zero is smaller than zero is smaller - zoomTo(ratio[, pivot]) Zoom and set the location of the center point - rotate(degree) Rotation similar css - rotateTo(degree) Rotate to absolute angle - scale(scaleX[, scaleY]),scaleX(scaleX),scaleY(scaleY) Scale a parameter represents the same scale value in horizontal and vertical direction - getData([rounded]) Return crop region based on original image!Original size!Location and size of rounded Default is false Indicates whether to display the rounded data. With these data, you can directly crop the original image - setData(data) Change the position and size of the clipping area based on the original image only if viewMode Valid if not 0 - getContainerData(),getImageData(),getCanvasData(),setCanvasData(data),getCropBoxData(),setCropBoxData(data) Data setting and obtaining of container, image container (canvas), image and clipping region relative to container - getCroppedCanvas([options]) Get one of the cropped pictures canvas object options Set this canvas Some data of - width,height,minWidth,minHeight,maxWidth,maxHeight,fillColor,imageSmoothingEnabled(Is the picture a smooth default true),imageSmoothingQuality(Image quality default low Also medium,high) - setAspectRatio(aspectRatio) Change the aspect ratio of the crop region - setDragMode([mode]) Set drag picture mode ## Event - ready Before rendering (the picture has been loaded cropper Instance is ready) - cropstart,cropmove,cropend,crop Start to draw clipping box (or canvas), middle of drawing clipping box (or canvas), end of clipping box (or canvas), and carry out clipping events event.detail.originalEvent,event.detail.action - When autoCrop by true crop Events will happen ready Trigger before - zoom Crop box zoom event
Reference material
Official github address: https://github.com/fengyuanchen/cropperjs
demo address: https://gitee.com/eightFlying/cropper-demo.git