头闻号

宁海县佳韵塑料厂

综合性公司

首页 > 新闻中心 > 科技常识:HTML5 canvas实现移动端上传头像拖拽裁剪效果
科技常识:HTML5 canvas实现移动端上传头像拖拽裁剪效果
发布时间:2024-10-06 01:43:34        浏览次数:5        返回列表

今天小编跟大家讲解下有关HTML5 canvas实现移动端上传头像拖拽裁剪效果 ,相信小伙伴们对这个话题应该有所关注吧,小编也收集到了有关HTML5 canvas实现移动端上传头像拖拽裁剪效果 的相关资料,希望小伙伴们看了有所帮助。

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

下图为裁剪后的效果:

html部分:

XML/HTML Code复制内容到剪贴板 <!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"> <title>上传头像</title> <metaname="renderer"content="webkit"> <metaname="viewport"content="width=device-width,initial-scale=1.0"> </head> <body> <divid="imgCrop"style="width:200px;height:200px;border:1pxsolid#ccc;overflow:hidden;"> <imgsrc=http://xyrl.com/skin/7ke/image/nopic.gif </div> <inputtype="file"accept="image/*"/> <buttonid="save">保存</button> <p>下面为剪切的图片:</p> <divid="imgShow"></div> </body> </html>

Javascript部分:

Javascript Code复制内容到剪贴板 var$imgCrop=$("#imgCrop"); var$img=$imgCrop.find("img"); varimg=$img[0]; varwidth=parseInt($imgCrop.css("width")); varheight=parseInt($imgCrop.css("height")); varstartX,startY,scale=1; varx=0,y=0; $("input").on("change",function(){ varfr=newFileReader(); varfile=this.files[0] //console.log(file); if(!/image\/\w+/.test(file.type)){ alert(file.name+"不是图片文件!"); return; } console.log(file); $img.removeAttr("heightwidth"); fr.readAsDataURL(file); fr.onload=function(){ img.src=fr.result; varwidthInit=img.width; if(img.width>img.height){ img.height=height; x=(width-img.width)/2; y=0; }else{ img.width=width; x=0; y=(height-img.height)/2; } scale=widthInit/img.width; 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(); varchangeX=e.changedTouches[0].pageX-startX+x; varchangeY=e.changedTouches[0].pageY-startY+y; move($(this),changeX,changeY); return; }); img.addEventListener("touchend",function(e){ varchangeX=e.changedTouches[0].pageX-startX+x; varchangeY=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; }); //确定目标图片的样式 functionmove(ele,x,y){ ele.css({ '-webkit-transform':'translate3d('+x+'px,'+y+'px,0)', 'transform':'translate3d('+x+'px,'+y+'px,0)' }); } $("#save").on("click",function(){ varurl=imageData($img); console.log(url); $("#imgShow").html("<imgsrc=http://xyrl.com/skin/7ke/image/nopic.gif }); //裁剪图片 functionimageData($img){ varcanvas=document.createElement('canvas'); varctx=canvas.getContext('2d'); canvas.width=width; canvas.height=height; ctx.drawImage(img,-x*scale,-y*scale,width*scale,height*scale,0,0,width,height); returncanvas.toDataURL(); }

以上就是本文的全部内容 希望对大家的学习有所帮助。

原文:http://www.cnblogs.com/yifengBlog/p/5265598.html

来源:爱蒂网