你的位置:首页 > 网页设计

[网页设计]html5 上传头像的裁剪

本示例使用HTML5 canvas,简单的编写了上传头像的裁剪效果,移动端支持拖拽后裁剪, 虽然样式不好看,但是功能还算全:

下图为裁剪后的效果:

html部分:

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>上传头像</title>  <meta name="renderer" content="webkit">  <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body><div id="imgCrop" style="width:200px;height:200px;border:1px solid #ccc;overflow:hidden;">  <img src="img/test.jpg" alt=""></div><input type="file" accept="image/*" /><button id="save">保存</button><p>下面为剪切的图片:</p><div id="imgShow"></div></body></html>

JavaScript部分:

var $imgCrop = $("#imgCrop");var $img = $imgCrop.find("img");var img = $img[0];var width = parseInt($imgCrop.css("width"));var height = parseInt($imgCrop.css("height"));var startX,startY;var x = 0,y = 0;$("input").on("change",function(){  var fr = new FileReader();  var file = this.files[0]  //console.log(file);  //console.log(file.size);  if(!/image\/\w+/.test(file.type)){    alert(file.name + "不是图片文件!");    return;  }  fr.readAsDataURL(file);  fr.onload = function(){    img.src = fr.result;    x = (img.width - width) > 0 ? (width - img.width)/2 : 0;    y = (img.height - height) > 0 ? (height - img.height)/2 : 0;    move($img, x, y);  };});img.addEventListener("touchstart",function(e){   startX = e.targetTouches[0].pageX;  startY = e.targetTouches[0].pageY;  return; }); img.addEventListener("touchmove",function(e){   e.preventDefault();   e.stopPropagation();   var changeX = e.changedTouches[0].pageX - startX + x;  var changeY = e.changedTouches[0].pageY - startY + y;  move($(this), changeX, changeY);  return;  }); img.addEventListener("touchend",function(e){   var changeX = e.changedTouches[0].pageX - startX + x;  var changeY = e.changedTouches[0].pageY - startY + y;  x = x + e.changedTouches[0].pageX - startX;  y = y + e.changedTouches[0].pageY - startY;  move($(this), changeX, changeY);  return;  }); //确定目标图片的样式function move(ele, x, y){  ele.css({    '-webkit-transform' : 'translate3d(' + x + 'px, ' + y + 'px, 0)',    'transform' : 'translate3d(' + x + 'px, ' + y + 'px, 0)'  });}$("#save").on("click",function(){  var url = imageData($img);  console.log(url);  $("#imgShow").html("<img src="+url+" />");;});//裁剪图片function imageData($img) {    var canvas = document.createElement('canvas');    var ctx = canvas.getContext('2d');    canvas.width = "200";    canvas.height = "200";    ctx.drawImage(img, -x, -y, width, height, 0, 0, width, height);    return canvas.toDataURL();  }