作为网站前段开发人员来讲,用户头像剪裁和上传是一个很经常使用的功能,通常这个功能涉及到图片的放大,缩小,移动,旋转,和剪裁。下面咱们来作一个完整的demo,剪裁后的图片以base64的形式返回,base64怎么上传到后台服务器,很简单,这里不作介绍。css
图片的操做:手机端操做和其余手机图片应用操做没有任何区别。PC端:经过鼠标的滚轮是实现图片的放大缩小,长按左键移动鼠标实现图片的移动,双击图片现实图片的旋转。html
在这个demo中,咱们使用Jquery的插件(jquery.photoClip.js)完成。【在个人下一个博客咱们分析下photoClip的源码实现】。在使用jquery.photoClip.js,咱们还得添加几个依赖插件:iscroll-zoom.js(实现图片的移动)、hammer.js、lrz.all.bundle.js。(这3个js扩展库,在我给出的demo下载地址一并给出)。下面是简单实现的源码:jquery
<!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>
若有兴趣能够加个人Q群一块儿讨论学习js,css,python爬虫等技术。(QQ群:512245829)web