search
HomeWeb Front-endVue.jsUse vue-cropper to crop images in the vue project

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

main.js

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

2. Image cropping

Use vue-cropper to crop images in the vue project

1. Introduce the VueCropper component and set related properties.

<div  style="display: flex;justify-content: center;align-items: center;width: 100%;height: 100%;">
            <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>
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 展示看到的截图框宽高
     }

❗️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(); //开始裁剪
},

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;
   // });
 },

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 //截图框高

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
}

1. Set the enter event on the "name" el-card <el-card></el-card>

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;
      });
    }

2. Set the leave event on all el-tabs in the outer layer of el-card<el-tabs></el-tabs>

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

❗️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
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

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

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

Vue.js vs. React: Project-Specific ConsiderationsVue.js vs. React: Project-Specific ConsiderationsApr 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 jump a tag to vueHow to jump a tag to vueApr 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.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software