如何用p5.js绘制可拖拽节点间的绿色直线连接线?
p5.js 拖拽节点并保持连接线实现方案
核心思路
把节点封装成独立对象,管理自身位置与拖拽状态;每次绘制时,直接根据两个节点的当前坐标绘制连接线,节点拖拽移动时,连接线会自动跟随更新。
完整代码实现
// 节点类 class Node { constructor(x, y) { this.x = x; this.y = y; this.size = 30; this.isDragging = false; } // 绘制节点 draw() { fill(255); stroke(0); strokeWeight(2); ellipse(this.x, this.y, this.size); // 节点中心连接标记 fill(0); ellipse(this.x, this.y, 6); } // 判断鼠标是否点击节点 checkMousePress(mx, my) { const d = dist(mx, my, this.x, this.y); if (d < this.size / 2) { this.isDragging = true; } } // 更新拖拽中节点的位置 updateDrag(mx, my) { if (this.isDragging) { this.x = mx; this.y = my; } } // 结束拖拽 endDrag() { this.isDragging = false; } } let nodeA, nodeB; function setup() { createCanvas(600, 400); // 初始化两个节点位置 nodeA = new Node(150, 200); nodeB = new Node(450, 200); } function draw() { background(240); // 先画绿色连接线 stroke(50, 200, 100); strokeWeight(3); line(nodeA.x, nodeA.y, nodeB.x, nodeB.y); // 再画节点(确保节点在连接线上方) nodeA.draw(); nodeB.draw(); } // 鼠标按下:判断是否选中节点 function mousePressed() { nodeA.checkMousePress(mouseX, mouseY); nodeB.checkMousePress(mouseX, mouseY); } // 鼠标拖拽:更新选中节点位置 function mouseDragged() { nodeA.updateDrag(mouseX, mouseY); nodeB.updateDrag(mouseX, mouseY); } // 鼠标释放:取消拖拽状态 function mouseReleased() { nodeA.endDrag(); nodeB.endDrag(); }
关键细节说明
- 绘制层级:先画连接线再画节点,避免节点被线条遮挡。
- 拖拽控制:通过
isDragging状态标记,只有被选中的节点才会跟随鼠标移动。 - 连接精度:直接使用节点中心坐标绘制线条,和示例图中节点中心的标记对应,保证连接位置准确。
内容的提问来源于stack exchange,提问作者Aolera
相关产品推荐
相关产品推荐

