search
HomeWeb Front-endJS TutorialHow to use cropper.js to encapsulate vue to implement the online image cropping component function (detailed tutorial)

This article mainly introduces the function of online image cropping component based on cropper.js encapsulating vue. It is very good and has reference value. Friends in need can refer to it.

The rendering is as shown below,

github:demo download

cropper.js

github:cropper.js

Official website (demo)

cropper.js installation

  • npm or bower installation

npm install cropper
# or
bower install cropper

clone download :Download address

git clone https://github.com/fengyuanchen/cropper.git

Reference cropper.js

Mainly reference cropper. js and cropper.css files

<script src="/path/to/jquery.js"></script><!-- jQuery is required -->
<link href="/path/to/cropper.css" rel="external nofollow" rel="stylesheet">
<script src="/path/to/cropper.js"></script>

Note: The jquery file must be introduced first before the cropper.js plug-in can be used

Simple use

Build the p container used for screenshots

<!-- Wrap the image or canvas element with a block element (container) -->
<p>
 ![](picture.jpg)
</p>

Add the style of the container and let the img fill the entire container (very important)

/* Limit image width to avoid overflow the container */
img {
 max-width: 100%; /* This rule is very important, please do not ignore this! */
}

Call the cropper.js method to initialize the screenshot Control

$(&#39;#image&#39;).cropper({
 aspectRatio: 16 / 9,
 crop: function(e) {
 // Output the result data for cropping image.
 console.log(e.x);
 console.log(e.y);
 console.log(e.width);
 console.log(e.height);
 console.log(e.rotate);
 console.log(e.scaleX);
 console.log(e.scaleY);
 }
});

For other detailed APIs, please refer to: github:cropper.js

Encapsulated into a vue component

Required for encapsulation into a vue component Problems solved

  • cropper.js related

Simulate input box click to select pictures and impose format and size restrictions on the selected pictures

Reselect image cropping

Confirm cropping and obtain image information in base64 format

  • vue related

Communication issues between non-parent and child components

Simulate the input box to click on the selected image and restrict the format and size of the selected image

Build a hidden input tag, Then simulate clicking on this input to achieve the function of selecting pictures

<!-- input框 -->
<input id="myCropper-input" type="file" :accept="imgCropperData.accept" ref="inputer" @change="handleFile">
//模拟点击
document.getElementById(&#39;myCropper-input&#39;).click();

Bind a method for monitoring content changes to the input, get the uploaded file, and perform format and size verification

// imgCropperData: {
// accept: &#39;image/gif, image/jpeg, image/png, image/bmp&#39;,
// }
handleFile (e) {
 let _this = this;
 let inputDOM = this.$refs.inputer;
 // 通过DOM取文件数据
 _this.file = inputDOM.files[0];
 // 判断文件格式
 if (_this.imgCropperData.accept.indexOf(_this.file.type) == -1) {
 _this.$Modal.error({
  title: &#39;格式错误&#39;,
  content: &#39;您选择的图片格式不正确!&#39;
 });
 return;
 }
 // 判断文件大小限制
 if (_this.file.size > 5242880) {
 _this.$Modal.error({
  title: &#39;超出限制&#39;,
  content: &#39;您选择的图片过大,请选择5MB以内的图片!&#39;
 });
 return;
 }
 var reader = new FileReader();
 // 将图片将转成 base64 格式
 reader.readAsDataURL(_this.file);
 reader.onload = function () {
 _this.imgCropperData.imgSrc = this.result;
 _this.initCropper();
 }
}

Reselect the picture for cropping

When you select the picture for the first time, you will definitely face the problem of needing to reselect the picture, then you will face the problem of how to replace the cropping frame For the picture in the above step, after selecting the picture, we got the main information of the picture through the FileRender() method. Now we need to rebuild the cropping box to solve the problem. Check the official demo given by cropper.js and find that the official method is to use The method of dynamically adding a cropping container is used for operation. Here we follow the official implementation.

// 初始化剪切
 initCropper () {
 let _this = this;
 // 初始化裁剪区域
 _this.imgObj = $(&#39;![](&#39; + _this.imgCropperData.imgSrc + &#39;)&#39;);
 let $avatarPreview = $(&#39;.avatar-preview&#39;);
 $(&#39;#myCropper-workspace&#39;).empty().html(_this.imgObj);
 _this.imgObj.cropper({
  aspectRatio: _this.proportionX / _this.proportionY,
  preview: $avatarPreview,
  crop: function(e) {

  }
 });
 }

Confirm cropping and obtain image information in base64 format

let $imgData = _this.imgObj.cropper(&#39;getCroppedCanvas&#39;)
imgBase64Data = $imgData.toDataURL(&#39;image/png&#39;);

Construct data for upload

// 构造上传图片的数据
let formData = new FormData();
// 截取字符串
let photoType = imgBase64Data.substring(imgBase64Data.indexOf(",") + 1);
//进制转换
const b64toBlob = (b64Data, contentType = &#39;&#39;, sliceSize = 512) => {
 const byteCharacters = atob(b64Data);
 const byteArrays = [];
 for(let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
 const slice = byteCharacters.slice(offset, offset + sliceSize);
 const byteNumbers = new Array(slice.length);
 for(let i = 0; i < slice.length; i++) {
  byteNumbers[i] = slice.charCodeAt(i);
 }
 const byteArray = new Uint8Array(byteNumbers);
 byteArrays.push(byteArray);
 }
 const blob = new Blob(byteArrays, {
 type: contentType
 });
 return blob;
}
const contentType = &#39;image/jepg&#39;;
const b64Data2 = photoType;
const blob = b64toBlob(b64Data2, contentType);
formData.append("file", blob, "client-camera-photo.png")
formData.append("type", _this.imgType)

Communication issues between non-parent and child components

In previous projects, communication parameters between parent and child components were commonly used, generally using two methods

Place parameters in the router, and then obtain them by calling route.params.xxx or route.query.xxx

Communicate through props

Here we use eventBus for components Communication between

Steps

1. Declare a bus component for B component to pass parameters to A component

//bus.js
import Vue from &#39;vue&#39;; 
export default new Vue();

2. Reference the bus component in component A and monitor its parameter changes in real time

// A.vue
import Bus from &#39;../../components/bus/bus.js&#39;
export default {
 components: { Bus },
 data () {},
 created: function () {
 Bus.$on(&#39;getTarget&#39;, imgToken => { 
  var _this = this;
  console.log(imgToken);
  ... 
 }); 
 }
}

3. Component B also references the bus component to pass the parameters to component A

// B.vue
// 传参
Bus.$emit(&#39;getTarget&#39;, imgToken);

Reference:

vue-$on
vue-$emit
vue.js road (4) - eventBus in vue2.0s implements sibling component communication

Complete code of vue picture selection and screenshot plug-in

<template>
 <p class="myCropper-container">
 <p id="myCropper-workspace">
  <p class="myCropper-words" v-show="!imgCropperData.imgSrc">请点击按钮选择图片进行裁剪</p>
 </p>
 <p class="myCropper-preview" :class="isShort ? &#39;myCropper-preview-short&#39; : &#39;myCropper-preview-long&#39;">
  <p class="myCropper-preview-1 avatar-preview">
  ![](!imgCropperData.imgUploadSrc ? &#39;/images/thumbnail/thumbnail-img.jpg&#39; : imgCropperData.imgUploadSrc)
  </p>
  <p class="myCropper-preview-2 avatar-preview">
  ![](!imgCropperData.imgUploadSrc ? &#39;/images/thumbnail/thumbnail-img.jpg&#39; : imgCropperData.imgUploadSrc)
  </p>
  <p class="myCropper-preview-3 avatar-preview">
  ![](!imgCropperData.imgUploadSrc ? &#39;/images/thumbnail/thumbnail-img.jpg&#39; : imgCropperData.imgUploadSrc)
  </p>
  <input id="myCropper-input" type="file" :accept="imgCropperData.accept" ref="inputer" @change="handleFile">
  <Button type="ghost" class="myCropper-btn" @click="btnClick">选择图片</Button>
  <Button type="primary" class="myCropper-btn" :loading="cropperLoading" @click="crop_ok">确认</Button>
 </p>
 </p>
</template>
<script>
 var ezjsUtil = Vue.ezjsUtil;
 import Bus from &#39;./bus/bus.js&#39; 
 export default {
 components: { Bus },
 props: {
  imgType: {
  type: String
  },
  proportionX: {
  type: Number
  },
  proportionY: {
  type: Number
  }
 },
 data () {
  return {
  imgCropperData: {
   accept: &#39;image/gif, image/jpeg, image/png, image/bmp&#39;,
   maxSize: 5242880,
   file: null, //上传的文件
   imgSrc: &#39;&#39;, //读取的img文件base64数据流
   imgUploadSrc: &#39;&#39;, //裁剪之后的img文件base64数据流
  },
  imgObj: null,
  hasSelectImg: false,
  cropperLoading: false,
  isShort: false,
  }
 },
 created: function () {
  let _this = this;
 },
 mounted: function () {
  let _this = this;
  // 初始化预览区域
  let maxWidthNum = Math.floor(300 / _this.proportionX);
  let previewWidth = maxWidthNum * _this.proportionX;
  let previewHeight = maxWidthNum * _this.proportionY;
  if (previewWidth / previewHeight <= 1.7) {
  previewWidth = previewWidth / 2;
  previewHeight = previewHeight / 2;
  _this.isShort = true;
  }
  // 设置最大预览容器的宽高
  $(&#39;.myCropper-preview-1&#39;).css(&#39;width&#39;, previewWidth + &#39;px&#39;);
  $(&#39;.myCropper-preview-1&#39;).css(&#39;height&#39;, previewHeight + &#39;px&#39;);
  // 设置中等预览容器的宽高
  $(&#39;.myCropper-container .myCropper-preview .myCropper-preview-2&#39;).css(&#39;width&#39;,( previewWidth / 2) + &#39;px&#39;);
  $(&#39;.myCropper-container .myCropper-preview .myCropper-preview-2&#39;).css(&#39;height&#39;, (previewHeight / 2) + &#39;px&#39;);
  // 设置最小预览容器的宽高
  $(&#39;.myCropper-container .myCropper-preview .myCropper-preview-3&#39;).css(&#39;width&#39;,( previewWidth / 4) + &#39;px&#39;);
  $(&#39;.myCropper-container .myCropper-preview .myCropper-preview-3&#39;).css(&#39;height&#39;, (previewHeight / 4) + &#39;px&#39;);
 },
 methods: {
  // 点击选择图片
  btnClick () {
  let _this = this;
  // 模拟input点击选择文件
  document.getElementById(&#39;myCropper-input&#39;).click();
  },
  // 选择之后的回调
  handleFile (e) {
  let _this = this;
  let inputDOM = this.$refs.inputer;
  // 通过DOM取文件数据
  _this.file = inputDOM.files[0];
  // 判断文件格式
  if (_this.imgCropperData.accept.indexOf(_this.file.type) == -1) {
   _this.$Modal.error({
   title: &#39;格式错误&#39;,
   content: &#39;您选择的图片格式不正确!&#39;
   });
   return;
  }
  // 判断文件大小限制
  if (_this.file.size > 5242880) {
   _this.$Modal.error({
   title: &#39;超出限制&#39;,
   content: &#39;您选择的图片过大,请选择5MB以内的图片!&#39;
   });
   return;
  }
  var reader = new FileReader();
  // 将图片将转成 base64 格式
  reader.readAsDataURL(_this.file);
  reader.onload = function () {
   _this.imgCropperData.imgSrc = this.result;
   _this.initCropper();
  }
  },
  // 初始化剪切
  initCropper () {
  let _this = this;
  // 初始化裁剪区域
  _this.imgObj = $(&#39;![](&#39; + _this.imgCropperData.imgSrc + &#39;)&#39;);
  let $avatarPreview = $(&#39;.avatar-preview&#39;);
  $(&#39;#myCropper-workspace&#39;).empty().html(_this.imgObj);
  _this.imgObj.cropper({
   aspectRatio: _this.proportionX / _this.proportionY,
   preview: $avatarPreview,
   crop: function(e) {
   }
  });
  _this.hasSelectImg = true;
  },
  // 确认
  crop_ok () {
  let _this = this, imgToken = null, imgBase64Data = null;
  // 判断是否选择图片
  if (_this.hasSelectImg == false) {
   _this.$Modal.error({
   title: &#39;裁剪失败&#39;,
   content: &#39;请选择图片,然后进行裁剪操作!&#39;
   });
   return false;
  }
  // 确认按钮不可用
  _this.cropperLoading = true;
  let $imgData = _this.imgObj.cropper(&#39;getCroppedCanvas&#39;)
  imgBase64Data = $imgData.toDataURL(&#39;image/png&#39;); 
  // 构造上传图片的数据
  let formData = new FormData();
  // 截取字符串
  let photoType = imgBase64Data.substring(imgBase64Data.indexOf(",") + 1);
  //进制转换
    const b64toBlob = (b64Data, contentType = &#39;&#39;, sliceSize = 512) => {
     const byteCharacters = atob(b64Data);
     const byteArrays = [];
     for(let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
      const slice = byteCharacters.slice(offset, offset + sliceSize);
      const byteNumbers = new Array(slice.length);
      for(let i = 0; i < slice.length; i++) {
       byteNumbers[i] = slice.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      byteArrays.push(byteArray);
     }
     const blob = new Blob(byteArrays, {
      type: contentType
     });
     return blob;
  }
  const contentType = &#39;image/jepg&#39;;
    const b64Data2 = photoType;
  const blob = b64toBlob(b64Data2, contentType);
  formData.append("file", blob, "client-camera-photo.png")
  formData.append("type", _this.imgType)
  // ajax上传
  $.ajax({
     url: _this.$nfs.uploadUrl,
     method: &#39;POST&#39;,
     data: formData,
     // 默认为true,设为false后直到ajax请求结束(调完回掉函数)后才会执行$.ajax(...)后面的代码
     async: false,
     // 下面三个,因为直接使用FormData作为数据,contentType会自动设置,也不需要jquery做进一步的数据处理(序列化)。
     cache: false,
     contentType: false,
   processData: false,
   type: _this.imgType,
     success: function(res) {
   let imgToken = res.data.token;
   _this.cropperLoading = false;
   // 传参
   Bus.$emit(&#39;getTarget&#39;, imgToken); 
     },
     error: function(error) {
   _this.cropperLoading = false;
   _this.$Modal.error({
    title: &#39;系统错误&#39;,
    content: &#39;请重新裁剪图片进行上传!&#39;
   });
     }
    });
  },
 }
 }
</script>
<style lang="less" scoped>
 .myCropper-container {
 height: 400px;
 }
 .myCropper-container #myCropper-input {
 width: 0px;
 height: 0px;
 }
 .myCropper-container #myCropper-workspace {
 width: 500px;
 height: 400px;
 border: 1px solid #dddee1;
 float: left;
 }
 // 裁剪图片未选择图片的提示文字
 .myCropper-container #myCropper-workspace .myCropper-words{
 text-align: center;
 font-size: 18px;
 padding-top: 180px;
 }
 // 裁剪图片的预览区域
 .myCropper-container .myCropper-preview-long {
 width: 300px;
 }
 .myCropper-container .myCropper-preview-short {
 width: 200px;
 }
 .myCropper-container .myCropper-preview {
 float: left;
 height: 400px;
 margin-left: 10px;
 }
 .myCropper-container .myCropper-preview .myCropper-preview-1 {
 border-radius: 5px;
 overflow: hidden;
 border: 1px solid #dddee1;
 box-shadow: 3px 3px 3px #dddee1;
 img {
  width: 100%;
  height: 100%;
 }
 }
 .myCropper-container .myCropper-preview .myCropper-preview-2 {
 margin-top: 20px;
 border-radius: 5px;
 overflow: hidden;
 border: 1px solid #dddee1;
 box-shadow: 3px 3px 3px #dddee1;
 img {
  width: 100%;
  height: 100%;
 }
 }
 .myCropper-container .myCropper-preview .myCropper-preview-3 {
 margin-top: 20px;
 border-radius: 5px;
 overflow: hidden;
 border: 1px solid #dddee1;
 box-shadow: 3px 3px 3px #dddee1;
 img {
  width: 100%;
  height: 100%;
 }
 }
 // 按钮
 .myCropper-btn {
 float: left;
 margin-top: 20px;
 margin-right: 10px;
 }
</style>

BY-LucaLJX

github: lucaljx

The above is what I compiled for you. I hope it will be helpful to everyone in the future.

Related articles:

JavaScript Gypsophila navigation bar implementation method

Detailed explanation from buying a domain name to using pm2 to deploy node.js project The whole process

layui select example of dynamically adding option

The above is the detailed content of How to use cropper.js to encapsulate vue to implement the online image cropping component function (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.