写在前面
–公司有这个需求,安排调查
–目前各大网站都是采用的-前端做裁剪返回坐标-由后端来做到裁剪
–而使用html-canvas画布可以直接前端裁剪并返回base64流-ajax可以直接下载保存
上代码:
注意配置好依赖-有一张png图片依赖
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title></title>
<link rel="stylesheet" href="css/jquery.Jcrop.min.css" />
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.Jcrop.min.js" type="text/javascript" charset="utf-8"></script>
<script>
$(function() {
var imgUrl;
$('input[type=file]').change(function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function() {
// 通过 reader.result 来访问生成的 DataURL
var url = reader.result;
setImageURL(url);
};
reader.readAsDataURL(file);
});
var image = new Image();
function setImageURL(url) {
image.src = url;
image.id = "target";
$("#img").append(image);
var cut = document.getElementById("cut");
var ctx = cut.getContext("2d");
image.onload = function() {
$('#target').Jcrop({
setSelect:[0, 0, 400, 400],
maxSize: [400, 400],
minSize: [400, 400],
onChange: updatePreview,
onSelect: updatePreview,
aspectRatio: 1
});
//裁剪过程中,每改变裁剪大小执行该函数
function updatePreview(c) {
if(parseInt(c.w) > 0) {
ctx.drawImage(image, c.x, c.y, c.w, c.h, 0, 0, 400, 400);
imgUrl = cut.toDataURL("image/png");
//.replace("image/png", "image/octet-stream")
console.log(c.x, c.y, c.w, c.h);
}
};
}
}
$("#submit").click(function(){
// console.log(imgUrl);
$.post("#",{img:imgUrl},function(result){
alert("OK");
});
window.location.href = imgUrl;
})
})
</script>
</head>
<body>
<canvas id="cut" width="400" height="400"></canvas>
<input type="file" />
<div id="img"></div>
<input type="button" id="submit" value="submit"/>
</body>
</html>
代码不是很长-基本已经做到最精简