Table of Contents
1. Installation
2. Image cropping
3. Echo the screenshot frame to the original image
4. Others
Home Web Front-end Vue.js Use vue-cropper to crop images in the vue project

Use vue-cropper to crop images in the vue project

Oct 31, 2022 pm 07:16 PM
vue vue.js vue3

vueHow to crop images in the project? The following article will introduce to you how to use vue-cropper to crop images. I hope it will be helpful to you!

Use vue-cropper to crop images in the vue project

Due to project needs, image cropping is required. The previous project has been implemented by cropper.js. Because vue is used this time, the vue-cropper component is used. It is very simple to use, but there are many pitfalls. (Learning video sharing: vue video tutorial)

1. Installation

npm install vue-cropper
Copy after login

main.js

import VueCropper from 'vue-cropper'
Vue.use(VueCropper)
Copy after login

2. Image cropping

Use vue-cropper to crop images in the vue project

1. Introduce the VueCropper component and set related properties.

<div    style="max-width:90%">
            <vueCropper
              @mouseenter.native="enter"
              @mouseleave.native="leave"
              ref="cropper"
              :img="uploadImg"
              :outputSize="option.size"
              :outputType="option.outputType"
              :info="true"
              :full="option.full"
              :canMove="option.canMove"
              :canMoveBox="option.canMoveBox"
              :original="option.original"
              :autoCrop="option.autoCrop"
              :fixed="option.fixed"
              :fixedNumber="option.fixedNumber"
              :centerBox="option.centerBox"
              :infoTrue="option.infoTrue"
              :fixedBox="option.fixedBox"
              style="background-image:none"
            ></vueCropper>
</div>
Copy after login
option: {
       info: true, // 裁剪框的大小信息
       outputSize: 0.8, // 裁剪生成图片的质量
       outputType: "jpeg", // 裁剪生成图片的格式
       canScale: false, // 图片是否允许滚轮缩放
       autoCrop: false, // 是否默认生成截图框
       fixedBox: false, // 固定截图框大小 不允许改变
       fixed: false, // 是否开启截图框宽高固定比例
       fixedNumber: [7, 5], // 截图框的宽高比例
       full: true, // 是否输出原图比例的截图
       canMove: false, //时候可以移动原图
       canMoveBox: true, // 截图框能否拖动
       original: false, // 上传图片按照原始比例渲染
       centerBox: false, // 截图框是否被限制在图片里面
       infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
     }
Copy after login

❗️The background of the default cropped image has an ugly mosaic. In fact, it uses a mosaic image as the background. To remove it, just set the style to remove the background image on VueCropperstyle ="background-image:none".

2. After the upload is completed, enter the VueCropper with the mouse to start cropping

Set on the VueCroper@mouseenter.native="enter "Event (⭐️ To use native events on components, you need to add the native keyword )

enter() {
 if (this.uploadImg == "") {
   return;
 }
 this.$refs.cropper.startCrop(); //开始裁剪
},
Copy after login

3. Leave VueCropper to stop cropping and get the cropped picture.

Set on VueCroper@mouseleave.native="leave"Event

leave() {
   this.$refs.cropper.stopCrop();//停止裁剪
   this.$refs.cropper.getCropData(data => { //获取截图的base64格式数据
     this.cutImg = data;
   });
   // this.$refs.cropper.getCropBlob(data => { //获取截图的Blob格式数据
   //   this.cutImg = data;
   // });
 },
Copy after login

I will crop it when I leave p. After clicking the crop button, I will pass the cropped image, and You don’t have to click the crop button to crop, because if I click the crop button to crop, the picture I get is not cropped. I don’t know why, so I came up with this method.
vue-cropper image cropping problem

3. Echo the screenshot frame to the original image

Use vue-cropper to crop images in the vue project
Basic principle:

this.$refs.cropper.getCropAxis() //获取截图框基于容器的坐标点 {x1: 174, x2: 131, y1: 86, y2: 58}
this.$refs.cropper.cropW  //截图框宽
this.$refs.cropper.cropH //截图框高
Copy after login

Use the above method to obtain the width, height and container-based coordinate points of the screenshot frame, then let VueCropper's automatic capture frame display and set the size and position of the automatic capture frame.

Take the name field as an example:

{
          id: 1,
          name: "姓名",
          cropInfo: {
            width: 108, //this.$refs.cropper.cropW
            height: 56, //this.$refs.cropper.cropH 
            offsetX: 174, //this.$refs.cropper.getCropAxis().x1
            offsetY: 86  //this.$refs.cropper.getCropAxis().y1
}
Copy after login

1. Set the enter event on the "name" el-card <el-card @mouseenter.native="enterCard(refWord) " />

enterCard(refWord) {
      this.$refs.cropper.goAutoCrop();//重新生成自动裁剪框
      this.$nextTick(() => {
        // if cropped and has position message, update crop box
        //设置自动裁剪框的宽高和位置
        this.$refs.cropper.cropOffsertX = refWord.cropInfo.offsetX;
        this.$refs.cropper.cropOffsertY = refWord.cropInfo.offsetY;
        this.$refs.cropper.cropW = refWord.cropInfo.width;
        this.$refs.cropper.cropH = refWord.cropInfo.height;
      });
    }
Copy after login

2. Set the leave event on all el-tabs in the outer layer of el-card<el-tabs @mouseleave.native="leaveCard()" / >

leaveCard() {
      this.$refs.cropper.clearCrop(); //取消裁剪框
    }
Copy after login

❗️Be careful not to set the leave event on el-card, otherwise when you move the mouse to the next el-card, the cropping box will be canceled and regenerated, causing the page to appear flickering phenomenon.

4. Others

  • Limit the screenshot frame to the image: https://github.com/xyxiao001/vue-cropper/issues /429
    Solution: centerBox is set to true, and it will only take effect when autoCrop=true

  • The project needs to send the position information and size of the crop box to the background. Let the background crop or perform OCR, but the cropped image after being sent to the background is always offset to the lower right corner: https://github.com/xyxiao001/vue-cropper/issues/386
    Solution: The image is scaled Yes, when passing position, you need to use position*scale.

  • . There is no problem in cropping most pictures, but there is always a deviation when cropping some pictures: https://github.com /xyxiao001/vue-cropper/issues/439
    Solution: It turns out that the default cropped image size is limited. The maximum width and height are 2000px. Set this value to 10000 and the problem is solved.

Use vue-cropper to crop images in the vue project

[Related video tutorial recommendations: vuejs entry tutorial, web front-end entry]

The above is the detailed content of Use vue-cropper to crop images in the vue project. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

How to jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

How to jump a tag to vue How to jump a tag to vue Apr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

What does the vue component pass value mean? What does the vue component pass value mean? Apr 07, 2025 pm 11:51 PM

Vue component passing values ​​is a mechanism for passing data and information between components. It can be implemented through properties (props) or events: Props: Declare the data to be received in the component and pass the data in the parent component. Events: Use the $emit method to trigger an event and listen to it in the parent component using the v-on directive.

See all articles