canvas 可以变形的四边形
手机中的演示
手机演示canvas 可移动的四边形
我封装了一个组件 专门用来写这个canvas
下面是html部分
我的画布大小是 长488,宽240
<view>
<canvas style="width: 488rpx; height: 240rpx;background: rgba(202, 202, 202, 1);" canvas-id="blendCanvas"
id="blendCanvas" @touchstart="touchstart" @touchmove="touchmove"></canvas>
</view>
data() {
return {
//data里面的 dot是正方形四个点的坐标 按顺序是: 左上 、右上 、右下 、左下
dot: [
[154, 50],
[242, 40],
[241, 85],
[154, 80]
],
//context 方便封装方法
context: uni.createCanvasContext('blendCanvas', this),
chooseDot: 0,//第几个点 0,1,2,3
isMove: true
}
},
mounted() {
//在mounted里面调用initDraw()方法
this.$nextTick(() => {
this.initDraw()
})
},
紫色的线是直角三角形的两条直角边
methods: {
initDraw() {
//绘制四边形
this.context.setStrokeStyle("#707070")
this.context.setLineWidth(0)
this.context.moveTo(this.dot[0][0], this.dot[0][1]);
this.context.lineTo(this.dot[1][0], this.dot[1][1]);
this.context.stroke()
this.context.lineTo(this.dot[2][0], this.dot[2][1]);
this.context.stroke()
this.context.lineTo(this.dot[3][0], this.dot[3][1]);
this.context.stroke()
this.context.lineTo(this.dot[0][0], this.dot[0][1]);
this.context.stroke()
this.context.fillStyle = "#707070";
this.context.fill();
this.context.draw()
},
//手指点击画布的时候
touchstart(e) {
//首先找哪个点离点击的位置最近
let x = e.changedTouches[0].x
let y = e.changedTouches[0].y
let minX = 0 //最近的点
let minArr = []
//遍历所有的点 选最近的点
for (let i = 0; i < this.dot.length; i++) {
/*Math.pow(Math.abs(this.dot[i][0] - x), 2) +
Math.pow(Math.abs(this.dot[i][1] - y), 2) 根据勾股定理获取到所有点距离电机的点的距离 进行比较 赋值到minX*/
if (minArr.length === 0) {
minArr[0] = Math.pow(Math.abs(this.dot[i][0] - x), 2) +
Math.pow(Math.abs(this.dot[i][1] - y), 2)
minX = i
} else {
if (Math.pow(Math.abs(this.dot[i][0] - x), 2) +
Math.pow(Math.abs(this.dot[i][1] - y), 2) < minArr[0]) {
minArr[0] = Math.pow(Math.abs(this.dot[i][0] - x), 2) +
Math.pow(Math.abs(this.dot[i][1] - y), 2)
minX = i
}
}
}
//进行判断 如果点击的点 距离最近的点太远 没有效果
if (minArr[0] > 500) {
this.isMove = false
} else {
this.isMove = true
this.chooseDot = minX
}
},
//手指移动的时候
touchmove(e) {
if (!this.isMove) {
//判断 距离太远直接return
return
}
let x = e.changedTouches[0].x
let y = e.changedTouches[0].y
//判断边界值
if (x <= 0) {
x = 0
}
if (y <= 0) {
y = 0
}
if (x >= 244) {
x = 244
}
if (y >= 120) {
y = 120
}
//找到的点开始动
this.dot[this.chooseDot][0] = x;
this.dot[this.chooseDot][1] = y;
this.initDraw()
}
}
这样就完成了
canvas 可改变的四边形