如何使用 bobril 框架移动 SVG 元素

How to move SVG element with bobril framework

我想在 bobril 中用鼠标移动一个 SVG 元素(圆圈)。我应该使用哪种生命周期组件方法?我尝试使用onPointerDown等等,但是这些方法只处理圈内的事件。我应该使用拖放还是有其他选项可以围绕整个 SVG 移动圆圈?

onPointerDownonPointerMoveonPointerUp 组件生命周期方法(更多信息在 bobril/index.ts IBobrilComponent 中)正是您所需要的,但需要一点点更多代码。

onPointerDown 方法中将 bobril b.registerMouseOwner 与您的上下文结合使用。

onPointerDown(ctx: ICtx, event: b.IBobrilPointerEvent) {
    b.registerMouseOwner(ctx);

    // Store the initial coordinates
    ctx.lastX = event.x;
    ctx.lastY = event.y;
    return true;
},

然后您的组件可以在 onPointerMove 方法中处理鼠标移动,甚至移动到元素之外。您只需要确定您仍然是当前所有者即可。所以你的方法可以看起来像像这样:

onPointerMove(ctx: ICtx, event: b.IBobrilPointerEvent) {
    if (!b.isMouseOwner(ctx))
        return false;

    if (ctx.lastX === event.x && ctx.lastY === event.y)
        return false;

    // Call handler if it is registered
    if (ctx.data.onMove) {
        ctx.data.onMove(event.x - ctx.lastX, event.y - ctx.lastY);
    }

    // Update coordinates 
    ctx.lastX = event.x;
    ctx.lastY = event.y;

    return true;
},

不要忘记释放你的注册。

onPointerUp(ctx: ICtx, event: b.IBobrilPointerEvent) {
    b.releaseMouseOwner();
    return true;
}

上面的示例将最后一个指针坐标存储到组件上下文中 ICtx。然后它可以用于向 onMove 处理程序提供 deltaXdeltaY。当您创建组件的节点时,可以通过输入数据注册此处理程序。