Canvas高级路径操作之拖拽对象的实现

2020-04-21 23:14:17易采站长站整理


const polygon = new Polygon(mouseStart.get('x'), mouseStart.get('y'), sideNum, radius);
polygonArray.push(polygon);//记录路径对象

在后续点击操作时,需要根据对应信息确定点击位置是否在路径之中

点击时,如何选取要拖拽的对象

首先获取点击时在

canvas中
的对应位置,我的代码用
mouseStart
记录
x
y

接着遍历
polygonArray
中的
polygon
,遍历中调用
polygon.createPath()
,通过
isPointInPath()
判断点击位置是否有路径,有的话
draggingPolygon = polygon
结束函数


const pos = positionInCanvas(e, canvasLeft, canvasTop);//获取在canvas中的像素位置
//记录鼠标起始点s
mouseStart.set('x', pos.x);
mouseStart.set('y', pos.y);
...
for (let polygon of polygonArray) {
polygon.createPath();
if (ctx.isPointInPath(mouseStart.get('x'), mouseStart.get('y'))) {
draggingPolygon = polygon;
return;
}
}

拖拽时的计算

这部分要完全理解推荐大家根据Demo中两个

console.log(draggingPolygon)
及代码进行调试,因为我们是在
mousemove
阶段,这个阶段触发函数非常频繁

我尽量用语言表达清楚

首先计算

move
时与
mouseStart
的距离,记为diff,有x轴上的
offsetX
,也有y轴上的
offsetY


const
pos = positionInCanvas(e, canvasLeft, canvasTop),
diff = new Map([
['offsetX', pos.x - mouseStart.get('x')],
['offsetY', pos.y - mouseStart.get('y')]]);

接着记录当前拖拽对象的

centerX
centerY
,记为temp


let
tempCenterX = draggingPolygon.centerX,
tempCenterY = draggingPolygon.centerY;

这里就是难理解的点,为什么要记录?继续往下看,后面会使用到。

根据

diff
中的offset,设置draggingPolygon新的中心位置


draggingPolygon.centerX += diff.get('offsetX');