效果图图下
cropper 图片裁剪
- 在
<head>
中导入 cropper.css
样式表:
<link rel="stylesheet" href="/assets/lib/cropper/cropper.css" />
- 在
<body>
的结束标签之前,按顺序导入如下的 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>
- 在卡片的
layui-card-bod
y 主体区域中,定义如下的 HTML
结构
<div class="row1">
<div class="cropper-box">
<img id="image" src="/assets/images/sample.jpg" />
</div>
<div class="preview-box">
<div>
<div class="img-preview w100"></div>
<p class="size">100 x 100</p>
</div>
<div>
<div class="img-preview w50"></div>
<p class="size">50 x 50</p>
</div>
</div>
</div
<!-- 第二行的按钮区域 -->
<div class="row2">
<button type="button" class="layui-btn">上传</button>
<button type="button" class="layui-btn layui-btn-danger">确定</button>
</div>
.layui-card-body {
width: 500px;
}
.row2 {
display: flex;
justify-content: flex-end;
margin-top: 20px;
}
.cropper-box {
width: 350px;
height: 350px;
background-color: cyan;
overflow: hidden;
}
.w100 {
width: 100px;
height: 100px;
background-color: gray;
}
.w50 {
width: 50px;
height: 50px;
background-color: gray;
margin-top: 50px;
}
.size {
font-size: 12px;
color: gray;
text-align: center;
}
.row1 {
display: flex;
}
.preview-box {
display: flex;
flex-direction: column;
flex: 1;
align-items: center;
}
.img-preview {
overflow: hidden;
border-radius: 50%;
}
- 实现基本裁剪效果
1.获取裁剪区域的 DOM 元素
2.配置选项: 纵横比、指定预览区域
3.创建裁剪区域
var $image = $('#image')
const options = {
aspectRatio: 1,
preview: '.img-preview'
}
$image.cropper(options
更换裁剪区域的图片
- 给文件选择框绑定 change 事件
- 用户选择了文件就会触发这个事件,通过
e.target.files
获取用户选择文件列表 - 通过索引0拿到用户选择的文件
- 将文件转化为路径
- 利用
$image
重新初始化裁剪区域
$('#file').on('change', function(e) {
var filelist = e.target.files
if (filelist.length === 0) {
return layer.msg('请选择照片!')
}
var file = e.target.files[0]
var imgURL = URL.createObjectURL(file)
$image
.cropper('destroy')
.attr('src', imgURL)
.cropper(options)
})