(H5)canvas实现裁剪图片和马赛克功能,以及又拍云上传图片
1.核心功能
此组件功能包含:
图片裁剪(裁剪框拖动,裁剪框改变大小);
图片马赛克(绘制马赛克,清除马赛克);
图片预览、图片还原(返回原图、返回处理图);
图片上传(获取签名、上传图片)。
2.核心逻辑
2.1图片裁剪
获取裁剪框(矩形)相对于画布的位置(左上)和裁剪框的height、width。获取(getimagedata)canvas相应位置的图片对象(imagedata)。清空canvas画布。在canvas画布的相应位置绘制(putimagedata)获取的图片对象(imagedata)。生成预览图。
2.2图片马赛克
马赛克的绘制,就是在以鼠标划过路径(画笔宽度)为中心的区域,重新绘制成其他的颜色。一般结果是,会取周围的相近的颜色。
取色方法:
1)比如现有一鼠标划过的点的坐标(x,y),定义一个矩形左上角坐标取(x,y),宽30px,高30px。我们把矩形宽高都除以5(分成5份,可以自定义为n份),所以现在是25个6px的小格子。每个小格子宽高都是6px。
2)然后,我们随机获取一个小格子,获取(getimagedata)这个小格子的图片对象(imagedata);再随机获取此图片对象上某个像素点(宽1px,高1px)的颜色color(rgba:imagedata.data[0],imagedata.data[1],imagedata.data[2],imagedata.data[3]);最后我们把第一个6x6px的小格子的每个像素点的颜色都设置为color。
3)其他24个小格子的颜色,遍历2步骤即可。
2.3清除马赛克
我们需要理解一个问题,不管是绘制马赛克,还是清除马赛克,其本质都是在绘制图片。我们在某个位置绘制了马赛克,清除的时候,就是把原图在当前位置的图片对象再画出来。就达到了清除的效果。所以,我们需要备份一个canvas,和原图一模一样,清除的时候,需要获取备份画布上对应位置的图像,绘制到马赛克的位置。
2.4图片预览
图片预览就是获取裁剪框的区域,获取区域内的图片对象。再绘制到画布上。
2.5图片还原至原图
清空画布,再次绘制原图
2.6还原至已操作图片
预览是保存画布图片对象(imagedata),清空画布,绘制保存的图片对象至画布
2.7图片上传
获取(todataurl)canvas图片路径,将获取到的base64图片转化为file对象。进行上传。
3.完整代码如下:
<template>
<div class="canvas-clip" :loading="loading">
<div
v-show="isdrop"
class="canvas-mainbox"
ref="canvas-mainbox"
id="canvas-mainbox"
@mousedown.stop="startmove($event)"
>
<div class="canvas-minbox left-up" @mousedown.stop="startresize($event,0)"></div>
<div class="canvas-minbox up" @mousedown.stop="startresize($event,1)"></div>
<div class="canvas-minbox right-up" @mousedown.stop="startresize($event,2)"></div>
<div class="canvas-minbox right" @mousedown.stop="startresize($event,3)"></div>
<div class="canvas-minbox right-down" @mousedown.stop="startresize($event,4)"></div>
<div class="canvas-minbox down" @mousedown.stop="startresize($event,5)"></div>
<div class="canvas-minbox left-down" @mousedown.stop="startresize($event,6)"></div>
<div class="canvas-minbox left" @mousedown.stop="startresize($event,7)"></div>
</div>
<!-- 画布 -->
<canvas
class="canvas-area"
ref="canvas"
id="canvas"
:width="canvaswidth"
:height="canvasheight"
@mousedown.stop="startmove($event)"
:class="{hoverpaint:isma,hoverclear:ismaclear}"
></canvas>
<!-- 备份画布 -->
<canvas class="canvas-copy" ref="canvascopy" :width="canvaswidth" :height="canvasheight"></canvas>
<div class="canvas-btns">
<button v-if="backbtn" @click="clipback">返回</button>
<button :class="{active:btnindex==0}" @click="sourceimg">原图</button>
<button :class="{active:btnindex==1}" @click="paintrectready" :disabled="isdisabled">马赛克</button>
<button :class="{active:btnindex==2}" @click="paintrectclearready" :disabled="isdisabled">橡皮擦</button>
<button :class="{active:btnindex==3}" @click="clipready" :disabled="isdisabled">裁剪</button>
<button :class="{active:btnindex==4}" @click="clipposition">预览</button>
<button @click="getsignature">上传</button>
<button class="close" @click="canvasclose()">x</button>
<!-- <div class="paint-size" v-if="ismaclear || isma">
<span>画笔大小</span>
<input :defaultvalue="masize" v-model="masize" max="100" min="1" type="range">
<span class="size-num">{{masize}}</span>
</div> -->
</div>
</div>
</template>
<script>
import axios from "axios";
import md5 from "js-md5";
import req from "../../axios/config";
export default {
props: ["imgurl"],
data() {
return {
resizefx: "",
moveprev: "",
canvaswidth: 800, // 画布宽
canvasheight: 600, // 画布高
loading: false,
isdrop: false, // 裁剪
isma: false, // 马赛克
masize: 30, // 马赛克大小
ismaclear: false, // 清除马赛克
backbtn: false, // 返回按钮
isdisabled: false,//禁用按钮
btnindex: 0,//当前按钮
mousex:'',// 鼠标位置
mousey:'',
clipele: "", // 裁剪框元素
canvasdatasession: "", // 预览前的画布信息
canvas: "", // 画布
ctx: "", // 画布上下文
canvascopy: "", // copy画布
ctxcopy: "", // copy画布上下文
uploadoption: { // 图片上传参数
path: "",
policy: "",
signature: "",
username: ""
}
};
},
mounted() {
this.clipele = this.$refs["canvas-mainbox"];
this.canvas = this.$refs["canvas"];
this.ctx = this.canvas.getcontext("2d");
this.canvascopy = this.$refs["canvascopy"];
this.ctxcopy = this.canvascopy.getcontext("2d");
this.draw();
},
methods: {
// 创建图片
draw() {
var img = new image();
img.setattribute('crossorigin', 'anonymous');
img.onload = () => {
this.ctx.drawimage(img, 0, 0, 800, 600);
this.ctxcopy.drawimage(img, 0, 0, 800, 600);
};
img.src = this.imgurl + '?time=' + new date().valueof();
},
//预览 计算裁剪框的位置(左上坐标)
clipposition() {
this.isdisabled = true;
this.backbtn = true;
this.isma = false;
this.ismaclear = false;
this.btnindex = 4;
//画布位置
var canvaspx = this.canvas.offsetleft,
canvaspy = this.canvas.offsettop;
if (this.isdrop) {
// 裁剪框位置
var clippx = this.clipele.offsetleft,
clippy = this.clipele.offsettop,
x = clippx - canvaspx,
y = clippy - canvaspy,
w = this.clipele.offsetwidth,
h = this.clipele.offsetheight,
// 预览图居中
positionx = 400 - this.clipele.offsetwidth / 2,
positiony = 300 - this.clipele.offsetheight / 2;
} else {
// 没有裁剪框,保存完整图片
var x = 0,
y = 0,
w = this.canvas.offsetwidth,
h = this.canvas.offsetheight,
// 预览图居中
positionx = 0,
positiony = 0;
}
var imagedata = this.ctx.getimagedata(x, y, w, h);
this.canvasdatasession = this.ctx.getimagedata(
0,
0,
this.canvaswidth,
this.canvasheight
);
this.ctx.clearrect(0, 0, this.canvaswidth, this.canvasheight);
this.ctx.putimagedata(imagedata, positionx, positiony);
this.clipele.style.display = "none";
this.canvascopy.style.display = "none";
},
// 返回预览前状态
clipback() {
this.btnindex = -1;
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) {
this.paintrectclear(e);
}
// 裁剪
if (this.isdrop) {
var targetdiv = $("#canvas-mainbox"),
offsetarr = targetdiv.offset();
var chax = e.pagex - this.moveprev[0],
chay = e.pagey - this.moveprev[1],
ox = parsefloat(targetdiv.css("left")),
oy = parsefloat(targetdiv.css("top"));
targetdiv.css({
left: ox + chax + "px",
top: oy + chay + "px"
});
this.moveprev = [e.pagex, e.pagey];
}
},
resizediv(e) {
e.preventdefault();
e.stoppropagation();
// 获取需要改变尺寸元素到页面的距离
var targetdiv = $("#canvas-mainbox"),
offsetarr = targetdiv.offset();
var eleswidth = targetdiv.width(),
elesheight = targetdiv.height(),
ox = parsefloat(targetdiv.css("left")),
oy = parsefloat(targetdiv.css("top"));
// 获取鼠标位置,和元素初始offset进行对比,
var chax = e.pagex - offsetarr.left,
chay = e.pagey - offsetarr.top;
switch (this.resizefx) {
case 0:
//如果移动距离接近宽度或高度,则不进行改变
if (chax >= eleswidth - 10 || chay >= elesheight - 10) {
return;
}
// 获得位置差(m-e),先设置宽度和高度,再设置位置
// 原始宽高+((m-e)*-1),原始位置+(m-e)
targetdiv.css({
width: eleswidth + chax * -1 + "px",
height: elesheight + chay * -1 + "px",
left: ox + chax + "px",
top: oy + chay + "px"
});
break;
case 1:
//如果移动距离接近宽度或高度,则不进行改变
if (chay >= elesheight - 10) {
return;
}
// 获得位置差(m-e),先设置宽度和高度,再设置位置
// 原始宽高+((m-e)*-1),原始位置+(m-e)
targetdiv.css({
height: elesheight + chay * -1 + "px",
top: oy + chay + "px"
});
break;
case 2:
//如果移动距离接近宽度或高度,则不进行改变
if (chax <= 10 || chay >= elesheight - 10) {
return;
}
// 获得位置差(m-e),先设置宽度和高度,设置位置
// 原始高+((m-e)*-1),原始宽+((m-e)),原始位置+(m-e)
targetdiv.css({
width: chax + "px",
height: elesheight + chay * -1 + "px",
top: oy + chay + "px"
});
break;
case 3:
//如果移动距离接近宽度或高度,则不进行改变
if (chax <= 10) {
return;
}
// 获得位置差(m-e),先设置宽度和高度,再设置位置
// 原始宽高+((m-e)*-1),原始位置+(m-e)
targetdiv.css({
width: chax + "px"
});
break;
case 4:
//如果移动距离接近宽度或高度,则不进行改变
if (chax <= 10 || chay <= 10) {
return;
}
// 获得位置差(m-e),先设置宽度和高度,再设置位置
// 原始宽高+((m-e)*-1),原始位置+(m-e)
targetdiv.css({
width: chax + "px",
height: chay + "px"
});
break;
case 5:
//如果移动距离接近宽度或高度,则不进行改变
if (chay <= 10) {
return;
}
// 获得位置差(m-e),先设置宽度和高度,再设置位置
// 原始宽高+((m-e)*-1),原始位置+(m-e)
targetdiv.css({
height: chay + "px"
});
break;
case 6:
//如果移动距离接近宽度或高度,则不进行改变
if (chax >= eleswidth - 10 || chay <= 10) {
return;
}
// 获得位置差(m-e),先设置宽度和高度,再设置位置
// 原始宽高+((m-e)*-1),原始位置+(m-e)
targetdiv.css({
width: eleswidth + chax * -1 + "px",
height: chay + "px",
left: ox + chax + "px"
});
break;
case 7:
//如果移动距离接近宽度或高度,则不进行改变
if (chax >= eleswidth - 10) {
return;
}
// 获得位置差(m-e),先设置宽度和高度,再设置位置
// 原始宽高+((m-e)*-1),原始位置+(m-e)
targetdiv.css({
width: eleswidth + chax * -1 + "px",
left: ox + chax + "px"
});
break;
default:
break;
}
},
// 裁剪
clipready() {
this.btnindex = 3;
this.isma = false;
this.isdrop = true;
this.ismaclear = false;
},
// 马赛克
paintrectready() {
this.btnindex = 1;
this.isma = true;
this.isdrop = false;
this.ismaclear = false;
},
// 橡皮擦
paintrectclearready() {
this.btnindex = 2;
this.isma = false;
this.isdrop = false;
this.ismaclear = true;
},
// 绘制马赛克
paintrect(e) {
var offt = this.canvas.offsettop, // 距离上边距离
offl = this.canvas.offsetleft, // 距离左边距离
x = e.clientx,
y = e.clienty;
if(this.mousex - x > this.masize/2 || x - this.mousex > this.masize/2 || this.mousey - y > this.masize/2 || y - this.mousey > this.masize/2){
var oimg = this.ctx.getimagedata(x - offl ,y - offt,this.masize,this.masize);
var w = oimg.width;
var h = oimg.height;
//马赛克的程度,数字越大越模糊
var num = 6;
//等分画布
var stepw = w/num;
var steph = h/num;
//这里是循环画布的像素点
for(var i=0;i<steph;i++){
for(var j=0;j<stepw;j++){
//获取一个小方格的随机颜色,这是小方格的随机位置获取的
var color = this.getxy(oimg,j*num+math.floor(math.random()*num),i*num+math.floor(math.random()*num));
//这里是循环小方格的像素点,
for(var k=0;k<num;k++){
for(var l=0;l<num;l++){
//设置小方格的颜色
this.setxy(oimg,j*num+l,i*num+k,color);
}
}
}
}
this.ctx.putimagedata(oimg,x - offl ,y - offt);
this.mousex = e.clientx
this.mousey = e.clienty
}
},
getxy(obj,x,y){
var w = obj.width;
var h = obj.height;
var d = obj.data;
var color = [];
color[0] = d[4*(y*w+x)];
color[1] = d[4*(y*w+x)+1];
color[2] = d[4*(y*w+x)+2];
color[3] = d[4*(y*w+x)+3];
return color;
},
setxy(obj,x,y,color){
var w = obj.width;
var h = obj.height;
var d = obj.data;
d[4*(y*w+x)] = color[0];
d[4*(y*w+x)+1] = color[1];
d[4*(y*w+x)+2] = color[2];
d[4*(y*w+x)+3] = color[3];
},
// 清除马赛克
paintrectclear(e) {
var offt = this.canvascopy.offsettop, // 距离上边距离
offl = this.canvascopy.offsetleft, // 距离左边距离
x = e.clientx,
y = e.clienty,
// 获取原图此位置图像数据
imagedata = this.ctxcopy.getimagedata(
x - offl,
y - offt,
this.masize,
this.masize
);
this.ctx.putimagedata(imagedata, x - offl, y - offt);
},
// 关闭画布
canvasclose(type, url) {
this.$emit("isshowimgchange", type, url);
}
}
};
</script>
<style scoped>
.canvas-clip {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 9010;
background: #000;
}
.canvas-mainbox {
position: absolute;
width: 400px;
height: 300px;
left: 50%;
top: 50%;
margin-left: -200px;
margin-top: -150px;
border: 1px solid #fff;
cursor: move;
z-index: 9009;
}
.canvas-minbox {
position: absolute;
width: 8px;
height: 8px;
background: #fff;
}
.left-up {
top: -4px;
left: -4px;
cursor: nw-resize;
}
.up {
top: -4px;
left: 50%;
margin-left: -4px;
cursor: n-resize;
}
.right-up {
top: -4px;
right: -4px;
cursor: ne-resize;
}
.right {
top: 50%;
margin-top: -4px;
right: -4px;
cursor: e-resize;
}
.right-down {
bottom: -4px;
right: -4px;
cursor: se-resize;
}
.down {
bottom: -4px;
left: 50%;
margin-left: -4px;
cursor: s-resize;
}
.left-down {
bottom: -4px;
left: -4px;
cursor: sw-resize;
}
.left {
top: 50%;
margin-top: -4px;
left: -4px;
cursor: w-resize;
}
.canvas-btns {
position: fixed;
right: 50px;
top: 30px;
z-index: 9003;
}
.canvas-btns button {
display: inline-blovk;
background: green;
cursor: pointer;
border: none;
width: 60px;
height: 30px;
line-height: 30px;
color: #fff;
font-size: 15px;
}
.canvas-btns button.active {
background: rgb(32, 230, 32);
}
.canvas-btns button.close {
background: rgb(230, 72, 32);
}
.canvas-copy {
position: absolute;
top: 50%;
left: 50%;
margin-top: -300px;
margin-left: -400px;
z-index: 9007;
}
.canvas-mosatic {
position: absolute;
top: 50%;
left: 50%;
margin-top: -300px;
margin-left: -400px;
z-index: 9009;
}
.canvas-area {
position: absolute;
top: 50%;
left: 50%;
margin-top: -300px;
margin-left: -400px;
z-index: 9008;
}
.paint-size{
margin-top: 20px;
font-size: 13px;
color: #fff;
height: 30px;
line-height: 30px;
text-align: right;
}
.paint-size input{
vertical-align: middle;
background: green;
}
.paint-size .size-num{
display: inline-block;
width: 15px;
}
.hoverclear{
cursor: url('./paint.png'),auto;
}
.hoverpaint{
cursor: url('./paint.png'),auto;
}
</style>
4.效果图如下:
5.组件是基于vue实现的,代码实现仓促,如有帮助或参考,请自行调试。欢迎留下意见和建议。
上一篇: Fiber 树的构建
下一篇: 简单谈谈js中Promise的用法