如何在PixiJS中使用顶点指针实现类似画图/Word的图形动态调整功能
PixiJS 顶点拖拽动态调整图形实现思路
- 第一步:数据与基础元素初始化
保留你原本使用的PIXI.Graphics绘制实例,额外定义数组存储图形所有顶点的坐标数据,后续所有图形绘制完全依赖该数组的坐标值,避免多份数据不一致。
为每个顶点生成独立的可交互控制点:用小号圆形PIXI.Graphics实现,开启interactive = true、buttonMode = true属性,给每个控制点绑定对应顶点的数组索引,方便拖拽时快速定位修改对应顶点数据。 - 第二步:拖拽交互逻辑实现
给所有控制点绑定pointerdown事件,触发时记录当前拖拽的顶点索引、鼠标按下位置和控制点的偏移量(避免拖拽时控制点跳转到鼠标位置),同时给全局舞台绑定pointermove和pointerup事件。pointermove触发时,根据鼠标实时坐标加偏移量更新对应索引的顶点坐标,同时同步更新对应控制点的位置,最后触发图形重绘。pointerup触发时,清空拖拽标记,移除全局的pointermove、pointerup监听,结束本次拖拽。 - 第三步:图形实时重绘逻辑
每次顶点更新后,先调用graphics.clear()清空原有绘制内容,再按最新的顶点数组重新执行绘制逻辑:多边形可直接循环顶点调用lineTo绘制后闭合路径,曲线类图形对应更新锚点/控制点坐标后重绘即可。 - 可选扩展:如果需要支持新增/删除顶点,可监听图形边线的点击事件,点击时在对应位置插入新顶点到数组,再触发重绘即可。
核心实现代码参考
// 初始化顶点坐标数据 const vertices = [{x: 100, y: 100}, {x: 300, y: 150}, {x: 200, y: 300}]; const shapeGraphics = new PIXI.Graphics(); const controlPoints = []; // 生成顶点控制点 vertices.forEach((vertex, index) => { const ctrlPoint = new PIXI.Graphics(); ctrlPoint.beginFill(0xff0000); ctrlPoint.drawCircle(0, 0, 6); ctrlPoint.endFill(); ctrlPoint.position.set(vertex.x, vertex.y); ctrlPoint.interactive = true; ctrlPoint.buttonMode = true; ctrlPoint.vertexIndex = index; ctrlPoint.on('pointerdown', handleDragStart); controlPoints.push(ctrlPoint); app.stage.addChild(ctrlPoint); }); // 图形重绘方法 function redrawShape() { shapeGraphics.clear(); shapeGraphics.beginFill(0x66ccff, 0.5); shapeGraphics.lineStyle(2, 0x000000); shapeGraphics.moveTo(vertices[0].x, vertices[0].y); for (let i = 1; i < vertices.length; i++) { shapeGraphics.lineTo(vertices[i].x, vertices[i].y); } shapeGraphics.closePath(); shapeGraphics.endFill(); } // 拖拽相关变量 let activeDragIndex = null; let dragOffset = {x: 0, y: 0}; function handleDragStart(event) { activeDragIndex = this.vertexIndex; const mousePos = event.data.getLocalPosition(app.stage); dragOffset.x = this.x - mousePos.x; dragOffset.y = this.y - mousePos.y; app.stage.on('pointermove', handleDragMove); app.stage.on('pointerup', handleDragEnd); } function handleDragMove(event) { if (activeDragIndex === null) return; const mousePos = event.data.getLocalPosition(app.stage); // 更新顶点数据 vertices[activeDragIndex].x = mousePos.x + dragOffset.x; vertices[activeDragIndex].y = mousePos.y + dragOffset.y; // 同步控制点位置 controlPoints[activeDragIndex].position.set( vertices[activeDragIndex].x, vertices[activeDragIndex].y ); // 重绘图形 redrawShape(); } function handleDragEnd() { activeDragIndex = null; app.stage.off('pointermove', handleDragMove); app.stage.off('pointerup', handleDragEnd); } // 初始渲染 redrawShape(); app.stage.addChild(shapeGraphics);
你要实现的效果参考如下:
内容的提问来源于stack exchange,提问作者Mitali Chaudhari
相关产品推荐
相关产品推荐

