圖片剪切是很多後台系統(如頭像上傳)常見的功能。本文示範如何封裝 jQuery 的 imgareaselect 插件,實現「框選區域 + 即時預覽 + 提交剪切參數」的完整流程。
以下是一個把插件封裝成類的 JavaScript 代碼:
sanshi_imgareaselect = function(pic_id,view_div_id){
this.pic_obj = jQuery("#"+pic_id);
this.view_div_id = view_div_id;
this.view_width = 100;
this.view_height = 100;
this.view_img_id = view_div_id+"_sanshi_img";
this.ias;
}
//建立預覽圖片
sanshi_imgareaselect.prototype.make_view_pic =function(){
var img_obj = jQuery(document.createElement("IMG"));
img_obj.attr("src",this.pic_obj.attr("src"));
img_obj.attr("id",this.view_img_id);
img_obj.attr("width",this.view_width);
img_obj.attr("height",this.view_height);
return img_obj;
}
//初始化函數
sanshi_imgareaselect.prototype.init=function(){
this.pic_width = this.pic_obj.attr("width");
this.pic_height = this.pic_obj.attr("height");
jQuery("#"+this.view_div_id).append(this.make_view_pic());
jQuery("#"+this.view_div_id).css({'width':this.view_width,'height':this.view_height,'overflow':'hidden'});
var fun_str="if ( selection.width && selection.height){ var scaleX = "+this.view_width+" / selection.width;var scaleY = "+this.view_height+" / selection.height;jQuery('#"+this.view_img_id+"').css({width: Math.round(scaleX * "+this.pic_width+"),height: Math.round(scaleY * "+this.pic_height+"),marginLeft: -Math.round(scaleX * selection.x1),marginTop: -Math.round(scaleY * selection.y1)});}";
var ias = this.pic_obj.imgAreaSelect({
fadeSpeed:200, autoHide:false, show:true, instance: true,
onInit:function(img, selection){ias.setSelection(100, 50, 250, 150, true);ias.update();},
onSelectEnd:function(img, selection){eval(fun_str);}
});
this.ias = ias;
}
//保存事件
sanshi_imgareaselect.prototype.save_pic=function(post_page,post_param){
var opt = this.ias.getSelection(true);
var post_arr = new Array();
jQuery.each(post_param,function(i,n){
var temp_str =i+"=";
temp_str += opt[n] ? opt[n] : n;
post_arr.push(temp_str);
});
post_page += post_page.lastIndexOf("?")<0 ? "?" : "&";
post_url = post_page+post_arr.join("&");
alert(post_url);
}
使用時,先宣告函數,並確保圖片載入完成後才執行初始化(避免在 FF3 下取不到寬高的 bug):
$(document).ready(function () {
var sanshi_img = new sanshi_imgareaselect("mypic","preview");
$("#mypic").load(function(){sanshi_img.init();});
$("#save_pic").click(function(){
sanshi_img.save_pic('1.php?n=6',{"id":5,"px1":"x1","py1":"y1",'px2':"x2","py2":"y2",'pwidth':"width",'pheight':"height"});
});
})
HTML 部分則放一個帶 id 的 img、一個預覽用的 div 與一個保存按鈕:
<div id="s">
<img id="mypic" src="scott-h-biram.jpg" title="mypic"/>
</div>
<div id="preview"></div>
<div><input type="button" id="save_pic" value="保存"></div>
這裡特別提醒:HTML 的 DOCTYPE 聲明不能省略,否則在 IE7 下會有問題。透過這套封裝,剪切時的縮放比例計算與預覽都被很好地封裝起來,只需傳入參數即可靈活應用。