Margarit Margarit - 2 months ago 8
TypeScript Question

How to move SVG element with bobril framework

I want to move an SVG element (circle) with mouse in bobril. Which lifecycle component method should I use? I tried to use

onPointerDown
and so on, but these methods only handle the events inside the circle. Should I use drag and drop or is there some other option to move the circle around the whole SVG?

Answer

The onPointerDown, onPointerMove and onPointerUp component lifecycle methods (more info in bobril/index.ts IBobrilComponent) are exactly what you need but with little bit more code.

Use bobril b.registerMouseOwner with your context in onPointerDown method.

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

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

Then your component can handle mouse move in onPointerMove method even moving outside the element. You only have to be sure that you are still the current owner. So your method can look e.g. like this:

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;
},

Don't forget to release your registration.

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

The example above stores the last pointer coordinates into the component context ICtx. Then it can be used to provide deltaX and deltaY to onMove handler. This handler can be registered by input data when you create the node of the component.

Comments