為了使用戶能自定義個人頭像,需要提供一個對上傳圖片的截圖功能,當前很多網站特別是SNS類網站都提供這樣的功能,非常實用。主要實現的形式有兩種,一種是flash截圖,另一種就是javascript截圖,兩種方法各有秋千,關于Flash截圖可以參考一下UcHome程序中頭像上傳功能,但這不是我要討論的話題,我這里主要是如何實現javascript截圖,利用jQuery的imgAreaSelect插件,輕松實現自定義頭像[avatar]javascript截圖功能。
一,準備:
兩個JS文件
1,jquery.js 下載:jquery.js
2,jquery.imgareaselect.js 下載:jquery.imgareaselect.js[imgareaselect-0.6.2.zip]
二,使用
function preview(img, selection){ var scaleX = 100 / selection.width; var scaleY = 100 / selection.height;
//動態小頭像 獲取當前選中框的寬度,高度,左邊框,右邊框
$('#biuuu + div > img').css({ width: Math.round(scaleX * 400) + 'px', height: Math.round(scaleY * 300) + 'px', marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px', marginTop: '-' + Math.round(scaleY * selection.y1) + 'px' }); }
//加載小頭像
$(document).ready(function () { $('<div><img src="http://www.gimoo.net/t/1903/biuuu.jpg" style="position: relative;" /></div>') .css({ float: 'left', position: 'relative', overflow: 'hidden', width: '100px', height: '100px' }) .insertAfter($('#biuuu')); });
//初始化加載
$(window).load(function () { $('#biuuu').imgAreaSelect({ aspectRatio: '1:1', onSelectChange: preview }); });
三,調用
<div class="container"> <p> <img id="biuuu" src="http://www.gimoo.net/t/1903/biuuu.jpg" title="biuuu" style="float: left; margin-right: 10px;" /> </p> </div>
使用上面的javascript截圖進行擴展可以實現很多的動態功能,jQuery提供的imgAreaSelect插件調用非常簡單,其它相關應用可參考:imgAreaSelect Examples
使用jQuery插件imgAreaSelect實現javascript截圖還是非常簡單的,基本上就是一個動態的圖像顯示,獲取源圖片的位置和選取框的大小[寬度和高度],輕松實現javascript截圖功能。