jQuery插件ImgAreaSelect实现头像上传预览和裁剪功能实例讲解一

2020-05-23 06:02:19易采站长站整理

<tr>
<td><b>Y<sub>2</sub>:</b></td>
<td><input type="text" id="y2" value="-" /></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>

  css样式:


<style>
#uploadPreview
{
width: 170px;
height: 170px;
background-position: center center;
background-size: cover;
border: 1px solid brown;
-webkit-box-shadow: 0 0 0px 0px rgba(0, 0, 0, 0);
display: inline-block;
}
</style>

第三步:实现图片的上传预览效果

思路:通过input 将图片的 src传给第一个img,然后再将第一个img的src传给第二个img的src


<script>
//通过input将图片路径传给第一个img
$("#uploadImage").on("change", function(){
// 得到一个参考文件列表
var files = !!this.files ? this.files : [];
// 如果没有选择任何文件,或者没有文件读到就返回
if (!files.length || !window.FileReader) return;
// 只有进行选择的文件是一个形象
if (/^image/.test( files[0].type)){
// 创建一个新的FileReader的实例
var reader = new FileReader();
// 读取本地文件作为一个DataURL
reader.readAsDataURL(files[0]);
// 当加载时,图像数据设置为背景的div
reader.onloadend = function(){
//给第一个img添加路径
$("#uploadPreview").attr("src",this.result);
//给第二个img添加路径
$("#tp").attr("src",this.result);
//开启裁剪功能
$('#uploadPreview ').imgAreaSelect( {handles:true, fadeSpeed:200, onSelectEnd : preview});
}
}
});
</script>

这样,就能够实现如下效果:

点击浏览

点击选择 :

第四步:实现区域选择功能


<script>
function preview(img, selection)
{
if(!selection.width || !selection.height) //判断选取区域不为空
return;
//分别取高宽比率
var scaleX = 100 / selection.width;
var scaleY = 100 / selection.height;
var img = new Image();
//传路径
img.src = document.getElementById('uploadPreview').src;
//给裁剪的图片定义高和宽
$('#preview img').css( {
width : Math.round(scaleX * 170), //170为第一个img的宽,不然截取的图片会有所缺失,可以自己试试
height: Math.round(scaleY * 170), //170为第一个img的高
marginLeft: -Math.round(scaleX * selection.x1),
marginTop: -Math.round(scaleY * selection.y1)