網站用戶頭像剪裁上傳完整案例

作爲網站前段開發人員來講,用戶頭像剪裁和上傳是一個很經常使用的功能,通常這個功能涉及到圖片的放大,縮小,移動,旋轉,和剪裁。下面咱們來作一個完整的demo,剪裁後的圖片以base64的形式返回,base64怎麼上傳到後臺服務器,很簡單,這裏不作介紹。css

圖片的操做:手機端操做和其餘手機圖片應用操做沒有任何區別。PC端:經過鼠標的滾輪是實現圖片的放大縮小,長按左鍵移動鼠標實現圖片的移動,雙擊圖片現實圖片的旋轉。html

demo下載地址:下載1 下載2python

圖片描述

在這個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

相關文章
相關標籤/搜索