在vue中对上传图进行上传前旋转操作

在vue中对上传的图片进行旋转操后生成新图片再上传到服务器

效果

实现

图片上传后将图片数据文件从blob格式转成canvas,生成新图即可

handRedit(file){ if (file.typeCode && file.typeCode<=4){file.typeCode+=1}else{file.typeCode=2} this.handleImgRotate(file,file.typeCode).toBlob(function(blob) { file.url =window.URL.createObjectURL(blob) },file.raw.type,0.7)},handleImgRotate(target,orientation){ var imgType=target.raw.type var imgObj = new Image(); imgObj.src = target.rootUrl imgObj.onload = () => { }; switch (Number(orientation)) { case 5: //为1,正常 var canvas = document.createElement('canvas') canvas.width=imgObj.naturalWidth canvas.height=imgObj.naturalHeight var ctx = canvas.getContext('2d') ctx.drawImage(imgObj, 0, 0, imgObj.naturalWidth, imgObj.naturalHeight); break; case 2: // 需要逆时针(向右)90度旋转 var canvas = document.createElement('canvas') canvas.width=imgObj.naturalHeight canvas.height=imgObj.naturalWidth var ctx = canvas.getContext('2d') ctx.rotate(90 * Math.PI / 180); ctx.drawImage(imgObj, 0, 0, imgObj.naturalWidth, -imgObj.naturalHeight); break; case 3: // 需要180度旋转 var canvas = document.createElement('canvas') canvas.width=imgObj.naturalWidth canvas.height=imgObj.naturalHeight var ctx = canvas.getContext('2d') ctx.rotate(180 * Math.PI / 180); ctx.drawImage(imgObj, -imgObj.naturalWidth, -imgObj.naturalHeight, imgObj.naturalWidth, imgObj.naturalHeight); break; case 4: // 需要顺时针(向左)90度旋转 var canvas = document.createElement('canvas') canvas.width=imgObj.naturalHeight canvas.height=imgObj.naturalWidth var ctx = canvas.getContext('2d') ctx.rotate(270 * Math.PI / 180); ctx.drawImage(imgObj, 0, 0, -imgObj.naturalWidth, imgObj.naturalHeight); break; default: var canvas = document.createElement('canvas') canvas.width=imgObj.naturalWidth canvas.height=imgObj.naturalHeight var ctx = canvas.getContext('2d') ctx.drawImage(imgObj, 0, 0, imgObj.naturalWidth, imgObj.naturalHeight); break; } return canvas},

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容