`

网站用户头像剪裁上传完整案例

阅读更多

做为网站前段开发人员来说,用户头像剪裁和上传是一个很常用的功能,一般这个功能涉及到图片的放大,缩小,移动,旋转,和剪裁。下面我们来做一个完整的demo,剪裁后的图片以base64的形式返回,base64怎么上传到后台服务器,很简单,这里不做介绍。

图片的操作:手机端操作和其他手机图片应用操作没有任何区别。 
PC端:通过鼠标的滚轮是实现图片的放大缩小,长按左键移动鼠标实现图片的移动,双击图片现实图片的旋转。

demo下载地址:下载1 下载2

头像上传实例

在这个demo中,我们使用jQuery的插件(jquery.photoClip.js)完成。【在我的下一个博客我们分析下photoClip的源码实现】。在使用jquery.photoClip.js,我们还得添加几个依赖插件:iscroll-zoom.js(实现图片的移动)、hammer.js、lrz.all.bundle.js。(这3个js扩展库,在我给出的demo下载地址一并给出)。下面是简单实现的源码:

<!doctype html>
<html lang="zh-CN" id="index">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="format-detection" content="telephone=no, email=no" />
<meta name="keywords" content="">
<meta name="description" content="">
<title>图片裁剪</title>
<style>
body {
    margin: 0;
    text-align: center;
}
#clipArea {
    margin: auto;
    height: 400px;
    width: 400px;
}
#file,
#clipBtn {
    margin: 20px;
}
#view {
    margin: 0 auto;
    width: 200px;
    height: 200px;
}
</style>
</head>
<body ontouchstart="">
<div id="clipArea"></div>
<input type="file" id="file">
<button id="clipBtn">截取</button>
<div id="view"></div>

<script src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
<script src="js/iscroll-zoom.js"></script> <!--实现图片的移动-->
<script src="js/hammer.js"></script>
<script src="js/lrz.all.bundle.js"></script>
<script src="js/jquery.photoClip.js"></script> <!--实现图片的剪裁-->
<script>
//document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
var clipArea = new bjj.PhotoClip("#clipArea", {     // #clipArea;包含剪裁图片div的ID
    size: [260, 260],   //剪裁完成的图片height,width
    outputSize: [640, 640], //剪裁框的height,width
    file: "#file",     //文件上传框ID
    view: "#view",     //预览div的ID
    ok: "#clipBtn",    //剪裁开始按钮ID
    loadStart: function() {
        console.log("照片读取中");
    },
    loadComplete: function() {
        console.log("照片读取完成");
    },
    clipFinish: function(dataURL) {
        console.log(dataURL);   //剪裁完成后返回的base64.可以直接上传至服务器。
    }
});
</script>
</body>
</html>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics