基于Html5 canvas实现裁剪图片和马赛克功能及又拍云上传图片 功能

2020-04-21 07:50:07易采站长站整理

this.backBtn = false;
this.isDisabled = false;
this.isDrop = false;
this.ctx.putImageData(this.canvasDataSession, 0, 0);
this.canvasCopy.style.display = "block";
},
// 原图
sourceImg() {
this.isDisabled = false;
this.btnIndex = 0;
this.backBtn = false;
this.isMa = false;
this.isDrop = false;
this.isMaClear = false;
var img = new Image();
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
img.setAttribute('crossOrigin', 'anonymous');
img.onload = () => {
this.ctx.drawImage(img, 0, 0, this.canvasWidth, this.canvasHeight);
};
img.src = this.imgUrl + '?time=' + new Date().valueOf();
this.canvasCopy.style.display = "block";
},
// 获取签名
getSignature() {
// canvas图片base64 转 File 对象
var dataURL = this.canvas.toDataURL("image/jpg"),
arr = dataURL.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
var obj = new Blob([u8arr], { type: mime }),
time = new Date().toGMTString(),
formData = new FormData();
formData.append("file", obj);
// 获取文件后缀
var suffix = formData.get("file").type.split("/")[1];
req
.get("/carsource-api/upyun/sign", { suffix: suffix })
.then(response => {
if (response.data.code === 0) {
this.uploadOption.path = response.data.data.path;
formData.append("policy", response.data.data.policy);
formData.append("authorization", response.data.data.signature);
this.updateImg(formData);
}
})
.catch(function(error) {});
},
// 上传
updateImg(formData) {
axios({
url: "http://v0.api.upyun.com/tmp-img",
method: "POST",
data: formData
}).then(response => {
if (response.data.code == 200) {
this.$message.success("图片修改成功");
this.canvasClose("upload", response.data.url.slice(4));
}
});
},
// 裁剪框缩放 移动
startResize(e, n) {
this.resizeFX = n;
$(document).mousemove(this.resizeDiv);
document.addEventListener("mouseup", this.stopResize);
},
stopResize(e) {
$(document).off("mousemove", this.resizeDiv);
document.removeEventListener("mouseup", this.stopResize);
},
startMove(e) {
this.movePrev = [e.pageX, e.pageY];
$(document).mousemove(this.moveDiv);
document.addEventListener("mouseup", this.stopMove);
},
stopMove(e) {
$(document).off("mousemove", this.moveDiv);
document.removeEventListener("mouseup", this.stopMove);
},
moveDiv(e) {
// 马赛克
if (this.isMa) {
this.paintRect(e);
}
// 清除马赛克
if (this.isMaClear) {