利用html5 canvas實現純前端上傳圖片的裁剪

今天跟你們分享一個前端裁剪圖片的方法.

許多網站都有設置用戶頭像的功能,用戶能夠選擇一張本地的圖片,而後用網站的裁剪工具進行裁剪,而後設置大小,位置合適的頭像.
固然,網上也有一些用js寫的諸如此類裁剪的插件,可是有許多都是前端將圖片的一些裁剪參數(如座標)傳給後臺,有java程序員進行真正的圖片裁剪.今天本身研究了一些,作了一個純前端裁剪的demo,以下:

1.html部分:
<div>
<input type="file" id="imgFile">
</div>
<div style="width: 300px;height: 300px;position: absolute;left: 300px;top: 0;display: inline-block">
<img id="demoImg" style="height: 300px;width: 300px" alt="">
<div style="width: 150px;height: 150px;border: 1px solid #4fb8e3;position: absolute;left: 0;top: 0;z-index: 1000" id="chooseBox"></div>
</div>
<div style="position: absolute;left: 700px;top: 0">
<canvas id="myCan" width="150" height="150"></canvas>
<button id="cut">裁剪文件</button>
<button id="btn">後臺返回獲取裁剪後的文件</button>
<img id="returnImg" alt="">
</div>

頁面初始截圖以下:html

2.第二步進行文件選擇後的預覽操做

var can=document.getElementById("myCan");
var btn=document.getElementById("btn");
var returnImg=document.getElementById("returnImg");
var ctx=can.getContext("2d");

$('#imgFile').change(function () {
var file=$('#imgFile')[0].files[0];
var reader=new FileReader();
reader.onload= function (e) {
$('#demoImg').attr('src', e.target.result);
};
reader.readAsDataURL(file);
});

3.進行裁剪

注意到任務圖像裏面有一個藍色邊框的選擇框(大小固定,沒有作縮放),將藍色選框移動到你須要的位置,點擊裁剪文件
$('#cut').click(function () {
var newX=$('#chooseBox').position().left*3.45;
var newY=$('#chooseBox').position().top*2.6;
var img=document.getElementById("demoImg");
console.log(newX,newY);
ctx.drawImage(img,newX,newY,150*3.45,150*2.6,0,0,150,150);
});


4.將裁剪後的圖片傳給後臺,並將返回的圖片展現
btn.onclick=function () {
var data=can.toDataURL();
data=data.split(',')[1];
data=window.atob(data);
var ia = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
ia[i] = data.charCodeAt(i);
}
var blob=new Blob([ia],{type:"image/png",endings:'transparent'});
var fd=new FormData();
console.log(blob);
fd.append('avatarFile',blob,'image.png');
var httprequest=new XMLHttpRequest();
httprequest.open('POST','/guest/avatar',true);
httprequest.send(fd);
httprequest.onreadystatechange= function () {
if(httprequest.status==200 && httprequest.readyState==4){
console.log(httprequest.responseText);
$('#returnImg').attr('src','/images/'+JSON.parse(httprequest.responseText).json);
}
};
};


整個demo的注意點有四點:

1.圖片上傳以後使用fileReader將圖片文件轉換成base64 png格式圖片,從而實現預覽

2.圖像選擇框的移動,mousedown,mouseup,mouseup事件的配合使用

3.html5 canvas實現圖片裁剪後的效果展現

4.利用html5 formData,將圖片文件轉換成blob對象,傳給後臺

完整源碼請移步個人github項目地址:
https://github.com/hyq2015/canvas_crop_img

參考文檔:http://blog.csdn.net/cuixiping/article/details/45932793

     http://www.javashuo.com/article/p-mnnyinaj-do.html http://blog.csdn.net/oscar999/article/details/36373183
相關文章
相關標籤/搜索