开源中国 APP,启动!这是你从没见过的全新版本”
1、图片通过canvas绘制
2、canvas旋转
3、canvas 转成blob 在实例化成文件
4、创建formData里面append放入文件和其他的参数,再调上传接口
代码语言:javascript复制 <div
style="
height: 600px;
display: flex;
justify-content: center;
align-items: center;
"
id="canvasWrap"
>
<!-- <img width="100%" :src="dialogImageUrl" alt="" > -->
<canvas id="picCanvas"></canvas>
</div>
<div>
<el-button size="medium" type="primary" @click="operateRotate">
旋转
</el-button>
</div>
代码语言:javascript复制 rotate(){
var img = new Image();
img.setAttribute("crossOrigin",'anonymous')
this.img = img
img.src = this.dialogImageUrl;
img.onload = ()=>{
console.log("rotate")
console.log(img.width)
console.log(img.height)
let maxSide = Math.max(img.width,img.height)
let canvas = document.getElementById("picCanvas")
this.canvas = canvas
let canvasWrap = document.getElementById("canvasWrap")
canvasWrap.appendChild(this.canvas)
// var canvas = document.createElement('canvas');
this.ctx = canvas.getContext("2d")
canvas.width = maxSide
canvas.height = maxSide
// 旋转并绘制图片
this.ctx.translate(maxSide/2,maxSide/2)
this.ctx.drawImage(img,-img.width/2,-img.height/2)
}
},
operateRotate(){
let img = this.img
// img.crossOrigin = "Anonymous"
// img.setAttribute("crossOrigin",'anonymous')
let ctx = this.ctx
let canvas = this.canvas
console.log(canvas.width)
console.log(canvas.height)
ctx.clearRect(-canvas.width/2,-canvas.height/2,canvas.width,canvas.height)
ctx.rotate(Math.PI / 2)
ctx.drawImage(img,-img.width/2,-img.height/2)
// var base64ImageData = canvas.toDataURL('image/jpeg')
// let blob = dataURItoBlob(base64ImageData);
// var file = new File([blob],'testPic.jpeg ',{ type: 'image/jpeg' })
canvas.toBlob(blob=>{
var file = new File([blob],'testPic.png',{ type: 'image/png' })
console.log(file)
let formData = new FormData();
formData.append("file", file);
formData.append(
"userId",
JSON.parse(sessionStorage.getItem("userInfo")).userCode
);
this.$axios.post("upload", formData).then(res => {
console.log(res.data);
if (res.data.errorCode == "00000") {
}
});
})
},