利用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
引用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>
##簡單使用
建構截圖所要用到的p容器
<!-- Wrap the image or canvas element with a block element (container) --> <p>  </p>
/* Limit image width to avoid overflow the container */ img { max-width: 100%; /* This rule is very important, please do not ignore this! */ }
$('#image').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); } });
#封裝成vue元件
封裝成vue元件中需解決的問題
cropper.js相關
- 模擬input框點擊選擇圖片並對選擇的圖片進行格式、大小限制
- 非父子元件之間的通訊問題
模擬input框點擊選擇圖片並對選擇的圖片進行格式、大小限制
建立一個隱藏的input標籤,然後模擬點擊此input,從而達到能選擇圖片的功能
<!-- input框 --> <input id="myCropper-input" type="file" :accept="imgCropperData.accept" ref="inputer" @change="handleFile"> //模拟点击 document.getElementById('myCropper-input').click();
// imgCropperData: { // accept: 'image/gif, image/jpeg, image/png, image/bmp', // } 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: '格式错误', content: '您选择的图片格式不正确!' }); return; } // 判断文件大小限制 if (_this.file.size > 5242880) { _this.$Modal.error({ title: '超出限制', content: '您选择的图片过大,请选择5MB以内的图片!' }); 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 = $(''); let $avatarPreview = $('.avatar-preview'); $('#myCropper-workspace').empty().html(_this.imgObj); _this.imgObj.cropper({ aspectRatio: _this.proportionX / _this.proportionY, preview: $avatarPreview, crop: function(e) { } }); }
確認裁剪並取得base64格式的圖片資訊
let $imgData = _this.imgObj.cropper('getCroppedCanvas') imgBase64Data = $imgData.toDataURL('image/png');
// 构造上传图片的数据 let formData = new FormData(); // 截取字符串 let photoType = imgBase64Data.substring(imgBase64Data.indexOf(",") + 1); //进制转换 const b64toBlob = (b64Data, contentType = '', 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 = 'image/jepg'; 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 'vue'; export default new Vue();
// A.vue import Bus from '../../components/bus/bus.js' export default { components: { Bus }, data () {}, created: function () { Bus.$on('getTarget', imgToken => { var _this = this; console.log(imgToken); ... }); } }
// B.vue // 传参 Bus.$emit('getTarget', imgToken);
vue-$emit
vue.js之路(4)——vue2.0s中eventBus實作兄弟元件通訊
JavaScript滿天星導航列實作方法 # 以上是利用cropper.js封裝vue如何實現線上圖片裁剪組件功能(詳細教學)的詳細內容。更多資訊請關注PHP中文網其他相關文章!<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 ? 'myCropper-preview-short' : 'myCropper-preview-long'">
<p class="myCropper-preview-1 avatar-preview">

</p>
<p class="myCropper-preview-2 avatar-preview">

</p>
<p class="myCropper-preview-3 avatar-preview">

</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 './bus/bus.js'
export default {
components: { Bus },
props: {
imgType: {
type: String
},
proportionX: {
type: Number
},
proportionY: {
type: Number
}
},
data () {
return {
imgCropperData: {
accept: 'image/gif, image/jpeg, image/png, image/bmp',
maxSize: 5242880,
file: null, //上传的文件
imgSrc: '', //读取的img文件base64数据流
imgUploadSrc: '', //裁剪之后的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;
}
// 设置最大预览容器的宽高
$('.myCropper-preview-1').css('width', previewWidth + 'px');
$('.myCropper-preview-1').css('height', previewHeight + 'px');
// 设置中等预览容器的宽高
$('.myCropper-container .myCropper-preview .myCropper-preview-2').css('width',( previewWidth / 2) + 'px');
$('.myCropper-container .myCropper-preview .myCropper-preview-2').css('height', (previewHeight / 2) + 'px');
// 设置最小预览容器的宽高
$('.myCropper-container .myCropper-preview .myCropper-preview-3').css('width',( previewWidth / 4) + 'px');
$('.myCropper-container .myCropper-preview .myCropper-preview-3').css('height', (previewHeight / 4) + 'px');
},
methods: {
// 点击选择图片
btnClick () {
let _this = this;
// 模拟input点击选择文件
document.getElementById('myCropper-input').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: '格式错误',
content: '您选择的图片格式不正确!'
});
return;
}
// 判断文件大小限制
if (_this.file.size > 5242880) {
_this.$Modal.error({
title: '超出限制',
content: '您选择的图片过大,请选择5MB以内的图片!'
});
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 = $('');
let $avatarPreview = $('.avatar-preview');
$('#myCropper-workspace').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: '裁剪失败',
content: '请选择图片,然后进行裁剪操作!'
});
return false;
}
// 确认按钮不可用
_this.cropperLoading = true;
let $imgData = _this.imgObj.cropper('getCroppedCanvas')
imgBase64Data = $imgData.toDataURL('image/png');
// 构造上传图片的数据
let formData = new FormData();
// 截取字符串
let photoType = imgBase64Data.substring(imgBase64Data.indexOf(",") + 1);
//进制转换
const b64toBlob = (b64Data, contentType = '', 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 = 'image/jepg';
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: 'POST',
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('getTarget', imgToken);
},
error: function(error) {
_this.cropperLoading = false;
_this.$Modal.error({
title: '系统错误',
content: '请重新裁剪图片进行上传!'
});
}
});
},
}
}
</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>

熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

華為手機如何實現雙微信登入?隨著社群媒體的興起,微信已成為人們日常生活中不可或缺的溝通工具之一。然而,許多人可能會遇到一個問題:在同一部手機上同時登入多個微信帳號。對於華為手機用戶來說,實現雙微信登入並不困難,本文將介紹華為手機如何實現雙微信登入的方法。首先,華為手機自帶的EMUI系統提供了一個很方便的功能-應用程式雙開。透過應用程式雙開功能,用戶可以在手機上同

程式語言PHP是一種用於Web開發的強大工具,能夠支援多種不同的程式設計邏輯和演算法。其中,實作斐波那契數列是一個常見且經典的程式設計問題。在這篇文章中,將介紹如何使用PHP程式語言來實作斐波那契數列的方法,並附上具體的程式碼範例。斐波那契數列是一個數學上的序列,其定義如下:數列的第一個和第二個元素為1,從第三個元素開始,每個元素的值等於前兩個元素的和。數列的前幾元

如何在華為手機上實現微信分身功能隨著社群軟體的普及和人們對隱私安全的日益重視,微信分身功能逐漸成為人們關注的焦點。微信分身功能可以幫助使用者在同一台手機上同時登入多個微信帳號,方便管理和使用。在華為手機上實現微信分身功能並不困難,只需要按照以下步驟操作即可。第一步:確保手機系統版本和微信版本符合要求首先,確保你的華為手機系統版本已更新至最新版本,以及微信App

在現今的軟體開發領域中,Golang(Go語言)作為一種高效、簡潔、並發性強的程式語言,越來越受到開發者的青睞。其豐富的標準庫和高效的並發特性使它成為遊戲開發領域的一個備受關注的選擇。本文將探討如何利用Golang來實現遊戲開發,並透過具體的程式碼範例來展示其強大的可能性。 1.Golang在遊戲開發中的優勢作為靜態類型語言,Golang正在建構大型遊戲系統

PHP遊戲需求實現指南隨著網路的普及和發展,網頁遊戲的市場也越來越火爆。許多開發者希望利用PHP語言來開發自己的網頁遊戲,而實現遊戲需求是其中一個關鍵步驟。本文將介紹如何利用PHP語言來實現常見的遊戲需求,並提供具體的程式碼範例。 1.創造遊戲角色在網頁遊戲中,遊戲角色是非常重要的元素。我們需要定義遊戲角色的屬性,例如姓名、等級、經驗值等,並提供方法來操作這些

在Golang中實現精確除法運算是一個常見的需求,特別是在涉及金融計算或其它需要高精度計算的場景中。 Golang的內建的除法運算子「/」是針對浮點數計算的,並且有時會出現精度遺失的問題。為了解決這個問題,我們可以藉助第三方函式庫或自訂函數來實現精確除法運算。一種常見的方法是使用math/big套件中的Rat類型,它提供了分數的表示形式,可以用來實現精確的除法運算

實在抱歉,我無法提供即時的程式設計指導,但我可以為你提供一篇程式碼範例,讓你更能理解如何使用PHP實作SaaS。以下是一篇1500字以內的文章,標題為《使用PHP實作SaaS:全面解析》。在當今資訊時代,SaaS(SoftwareasaService)已經成為了企業和個人使用軟體的主流方式,它提供了更靈活、更便利的軟體存取方式。透過SaaS,用戶無需在本地

標題:利用Golang實現資料匯出功能詳解隨著資訊化程度的提升,許多企業和組織需要將儲存在資料庫中的資料匯出到不同的格式中,以便進行資料分析、報表產生等用途。本文將介紹如何利用Golang程式語言實作資料匯出功能,包括連接資料庫、查詢資料和匯出資料到檔案的詳細步驟,並提供具體的程式碼範例。連接資料庫首先,我們需要使用Golang中提供的資料庫驅動程序,例如da
