1. 基本使用步驟
1. 在 <head> 中導(dǎo)入 cropper.css 樣式表:
<link rel="stylesheet" href="/assets/lib/cropper/cropper.css" />
2 在 <body> 的結(jié)束標(biāo)簽之前,按順序?qū)肴缦碌?js 腳本:
<script src="/assets/lib/jquery.js"></script>
<script src="/assets/lib/cropper/Cropper.js"></script>
<script src="/assets/lib/cropper/jquery-cropper.js"></script>
3在卡片的 layui-card-body 主體區(qū)域中,定義如下的 HTML 結(jié)構(gòu):
<!-- 第一行的圖片裁剪和預(yù)覽區(qū)域 -->
<div class="row1">
<!-- 圖片裁剪區(qū)域 -->
<div class="cropper-box">
<!-- 這個(gè) img 標(biāo)簽很重要,將來(lái)會(huì)把它初始化為裁剪區(qū)域 -->
<img id="image" src="/assets/images/sample.jpg" />
</div>
<!-- 圖片的預(yù)覽區(qū)域 -->
<div class="preview-box">
<div>
<!-- 寬高為 100px 的預(yù)覽區(qū)域 -->
<div class="img-preview w100"></div>
<p class="size">100 x 100</p>
</div>
<div>
<!-- 寬高為 50px 的預(yù)覽區(qū)域 -->
<div class="img-preview w50"></div>
<p class="size">50 x 50</p>
</div>
</div>
</div>
<!-- 第二行的按鈕區(qū)域 -->
<div class="row2">
<button type="button" class="layui-btn">上傳</button>
<button type="button" class="layui-btn layui-btn-danger">確定</button>
</div>
4 美化的樣式:
/* 設(shè)置卡片主體區(qū)域的寬度 */
.layui-card-body {
width: 500px;
}
/* 設(shè)置按鈕行的樣式 */
.row2 {
display: flex;
justify-content: flex-end;
margin-top: 20px;
}
/* 設(shè)置裁剪區(qū)域的樣式 */
.cropper-box {
width: 350px;
height: 350px;
background-color: cyan;
overflow: hidden;
}
/* 設(shè)置第一個(gè)預(yù)覽區(qū)域的樣式 */
.w100 {
width: 100px;
height: 100px;
background-color: gray;
}
/* 設(shè)置第二個(gè)預(yù)覽區(qū)域的樣式 */
.w50 {
width: 50px;
height: 50px;
background-color: gray;
margin-top: 50px;
}
/* 設(shè)置預(yù)覽區(qū)域下方文本的樣式 */
.size {
font-size: 12px;
color: gray;
text-align: center;
}
/* 設(shè)置圖片行的樣式 */
.row1 {
display: flex;
}
/* 設(shè)置 preview-box 區(qū)域的的樣式 */
.preview-box {
display: flex;
flex-direction: column;
flex: 1;
align-items: center;
}
/* 設(shè)置 img-preview 區(qū)域的樣式 */
.img-preview {
overflow: hidden;
border-radius: 50%;
}
5 實(shí)現(xiàn)基本裁剪效果:
// 1.1 獲取裁剪區(qū)域的 DOM 元素
var $image = $('#image')
// 1.2 配置選項(xiàng)
const options = {
// 縱橫比
aspectRatio: 1,
// 指定預(yù)覽區(qū)域
preview: '.img-preview'
}
// 1.3 創(chuàng)建裁剪區(qū)域
$image.cropper(options)
2. 更換裁剪的圖片
1 拿到用戶(hù)選擇的文件
var file = e.target.files[0]
2根據(jù)選擇的文件,創(chuàng)建一個(gè)對(duì)應(yīng)的 URL 地址:
var newImgURL = URL.createObjectURL(file)
3 先銷(xiāo)毀舊的裁剪區(qū)域,再重新設(shè)置圖片路徑,之后再創(chuàng)建新的裁剪區(qū)域:
$image
.cropper('destroy') // 銷(xiāo)毀舊的裁剪區(qū)域
.attr('src', newImgURL) // 重新設(shè)置圖片路徑
.cropper(options) // 重新初始化裁剪區(qū)域
3. 將裁剪后的圖片,輸出為 base64 格式的字符串
var dataURL = $image
.cropper('getCroppedCanvas', { // 創(chuàng)建一個(gè) Canvas 畫(huà)布
width: 100,
height: 100
})
.toDataURL('image/png') // 將 Canvas 畫(huà)布上的內(nèi)容,轉(zhuǎn)化為 base64 格式的字符串
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。