时间:2021-03-16 10:21:46 | 栏目:vue | 点击:次
预览链接点击预览
效果图如下所示,大家感觉不错,请参考实现代码。
需求
实现步骤
methods:funName() - 对应源码中methods中的funName方法
data:dataName - 对应源码中data中的dataName数据
1. 图片选择与读取
2. 在canvas中展示图片
需要掌握的 canvas 相关知识:
# 语法 ctx.drawImage(image, dx, dy); ctx.drawImage(image, dx, dy, dWidth, dHeight); ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight); # 参数 image # 绘制的元素(可以为HTMLImageElement,HTMLVideoElement,或者 HTMLCanvasElement。) dx,dy # 目标画布(destination canvas)左上角的坐标 dWidth,dHeight # 目标画布(destination canvas)上绘制图像宽高 sx,sy # 源画布(source canvase)左上角的坐标 sWidth,sHeight # 源画布(source canvase)选择的图像宽高
5.剪裁图片 ctx.clip() ;
具体步骤:
裁剪区域vue data示意图:
3. 移动裁剪框
知识点: onmousedown、onmousemove、onmouseup
具体实现:
methods:drag()
记录鼠标坐标,鼠标移动根据偏移量计算圆心位置。
canvas.onmousedown = e => { let [lastX, lastY] = [e.offsetX, e.offsetY]; self.movement = true; canvas.onmousemove = e => { self.circleCenter = { X: self.cropperCanvasSize.width > 2 * self.slectRadius ? self.circleCenter.X + (e.offsetX - lastX) : self.cropperCanvasSize.width / 2, Y: self.cropperCanvasSize.height > 2 * self.slectRadius ? self.circleCenter.Y + (e.offsetY - lastY) : self.cropperCanvasSize.height / 2 }; self.renderCropperImg(); [lastX, lastY] = [e.offsetX, e.offsetY]; }; canvas.onmouseup = e => { self.movement = false; canvas.onmousemove = null; canvas.onmouseup = null; }; };
4. 上传图片至服务器
知识点:
具体实现:
methods:upload() this.$refs.preview.toBlob((blob)=> { const url = URL.createObjectURL(blob); const formData = new FormData(); formData.append(this.uploadProps.name, blob, `${Date.now()}.png`); if(this.data){ Object.keys(this.uploadProps.data).forEach(key => { formData.append(key, this.uploadProps.data[key]); }); } const request = new XMLHttpRequest(); request.open("POST", this.uploadProps.action, true); request.send(formData); request.onreadystatechange = () => { if (request.readyState === 4 && request.status === 200) { // ... } }; });
总结