搜尋
首頁web前端js教程利用cropper.js封裝vue如何實現線上圖片裁剪組件功能(詳細教學)

這篇文章主要介紹了基於cropper.js封裝vue實現在線圖片裁剪組件功能,非常不錯,具有參考借鑒價值,需要的朋友可以參考下

效果圖如下所示,

github:demo下載

cropper.js

github:cropper.js

官網(demo)

cropper.js 安裝

  • #npm或bower安裝

  • ##
    npm install cropper
    # or
    bower install cropper
clone下載:下載地址

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

引用cropper.js##主要引用cropper. js跟cropper.css兩個文件

<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>

注意:必須先引入jquery文件,才能使用cropper.js插件

##簡單使用

建構截圖所要用到的p容器

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

新增容器的樣式,讓img填滿整個容器(很重要)

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

呼叫cropper.js方法,初始化截圖控制項

$(&#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);
 }
});

其他詳細api請參考:github:cropper.js

#封裝成vue元件

封裝成vue元件中需解決的問題

cropper.js相關
  • 模擬input框點擊選擇圖片並對選擇的圖片進行格式、大小限制
重新選擇圖片裁切

確認裁切並取得base64格式的圖片資訊

vue相關
  • 非父子元件之間的通訊問題

模擬input框點擊選擇圖片並對選擇的圖片進行格式、大小限制

建立一個隱藏的input標籤,然後模擬點擊此input,從而達到能選擇圖片的功能

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

給input綁定一個監聽內容變化的方法,拿到上傳的文件,並進行格式、大小校驗

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

重新選擇圖片裁切

當第一次選擇圖片之後,肯定會面臨需要重選圖片的問題,那麼就會面臨如何替換掉裁切框中的圖片,上面的步驟選擇了圖片後通過FileRender()方法拿到了圖片的主要信息,現在就需要重新構建裁剪框就可以解決問題了,查看cropper.js給出的官方demo,發現官方是使用動態添加裁剪容器的方法,進行操作的,這裡我們仿照官方進行實作。

// 初始化剪切
 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) {

  }
 });
 }

確認裁剪並取得base64格式的圖片資訊

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)
#非父子元件之間的通訊問題

在先前的專案中,常用到父子元件之間的通訊傳參,一般用兩種方法

在router裡面放置參數,然後透過呼叫route.params.xxx或route.query.xxx進行取得

透過props進行通訊

這裡我們使用eventBus進行元件之間的通訊

步驟

#1.聲明一個bus元件用於B元件把參數傳遞給A元件

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

2.在A元件中引用bus元件,並即時監聽其參數變化

// 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.B元件中同樣引用bus元件,來把參數傳給A元件

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

參考:

vue-$on

vue-$emit

vue.js之路(4)——vue2.0s中eventBus實作兄弟元件通訊



#vue選圖截圖外掛完整程式碼

<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

上面是我整理給大家的,希望今後會對大家有幫助。

相關文章:

JavaScript滿天星導航列實作方法

詳解從買網域到使用pm2部署node.js項目全過程

layui select動態新增option的實例

#

以上是利用cropper.js封裝vue如何實現線上圖片裁剪組件功能(詳細教學)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
node.js流帶打字稿node.js流帶打字稿Apr 30, 2025 am 08:22 AM

Node.js擅長於高效I/O,這在很大程度上要歸功於流。 流媒體匯總處理數據,避免內存過載 - 大型文件,網絡任務和實時應用程序的理想。將流與打字稿的類型安全結合起來創建POWE

Python vs. JavaScript:性能和效率注意事項Python vs. JavaScript:性能和效率注意事項Apr 30, 2025 am 12:08 AM

Python和JavaScript在性能和效率方面的差異主要體現在:1)Python作為解釋型語言,運行速度較慢,但開發效率高,適合快速原型開發;2)JavaScript在瀏覽器中受限於單線程,但在Node.js中可利用多線程和異步I/O提升性能,兩者在實際項目中各有優勢。

JavaScript的起源:探索其實施語言JavaScript的起源:探索其實施語言Apr 29, 2025 am 12:51 AM

JavaScript起源於1995年,由布蘭登·艾克創造,實現語言為C語言。 1.C語言為JavaScript提供了高性能和系統級編程能力。 2.JavaScript的內存管理和性能優化依賴於C語言。 3.C語言的跨平台特性幫助JavaScript在不同操作系統上高效運行。

幕後:什麼語言能力JavaScript?幕後:什麼語言能力JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript在瀏覽器和Node.js環境中運行,依賴JavaScript引擎解析和執行代碼。 1)解析階段生成抽象語法樹(AST);2)編譯階段將AST轉換為字節碼或機器碼;3)執行階段執行編譯後的代碼。

Python和JavaScript的未來:趨勢和預測Python和JavaScript的未來:趨勢和預測Apr 27, 2025 am 12:21 AM

Python和JavaScript的未來趨勢包括:1.Python將鞏固在科學計算和AI領域的地位,2.JavaScript將推動Web技術發展,3.跨平台開發將成為熱門,4.性能優化將是重點。兩者都將繼續在各自領域擴展應用場景,並在性能上有更多突破。

Python vs. JavaScript:開發環境和工具Python vs. JavaScript:開發環境和工具Apr 26, 2025 am 12:09 AM

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。

JavaScript是用C編寫的嗎?檢查證據JavaScript是用C編寫的嗎?檢查證據Apr 25, 2025 am 12:15 AM

是的,JavaScript的引擎核心是用C語言編寫的。 1)C語言提供了高效性能和底層控制,適合JavaScript引擎的開發。 2)以V8引擎為例,其核心用C 編寫,結合了C的效率和麵向對象特性。 3)JavaScript引擎的工作原理包括解析、編譯和執行,C語言在這些過程中發揮關鍵作用。

JavaScript的角色:使網絡交互和動態JavaScript的角色:使網絡交互和動態Apr 24, 2025 am 12:12 AM

JavaScript是現代網站的核心,因為它增強了網頁的交互性和動態性。 1)它允許在不刷新頁面的情況下改變內容,2)通過DOMAPI操作網頁,3)支持複雜的交互效果如動畫和拖放,4)優化性能和最佳實踐提高用戶體驗。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。