Home > Blockchain >  Dragging SVG element in Angular
Dragging SVG element in Angular

Time:09-14

I have an SVG with some elements in my Angular app, and I want to drag some elements in it. I wrote something like this:

component.html

<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" (mouseleave)="leave()">
    <circle *ngFor="let d of drawings" r="3" fill="red" [attr.cx]="d.x" [attr.cy]="d.y" (mousedown)="down($event, d)" (mouseup)="up()" (mousemove)="move($event)"></circle>
</svg>

component.ts

drawings: any[] = [
    { x: 310, y: 210 },
    { x: 56, y: 17 },
    { x: 220, y: 365 }
];

selectedElement = null;
sX = 0;
sY = 0;

down(e: any, d: any) {
    const isMouse = !e.type.indexOf('mouse');

    if (isMouse && e.which !== 1 && e.buttons !== 0) {
        return;
    }

    this.selectedElement = d;
    
    this.sX = e.layerX;
    this.sY = e.layerY;
}

up() {
    this.selectedElement = null;
}

leave() {
    this.selectedElement = null;
}

move(e: any) { 
    if (this.selectedElement != null) {
        e.preventDefault();
        
        this.selectedElement.x  = e.layerX - this.sX;
        this.selectedElement.y  = e.layerY - this.sY;

        this.sX = e.layerX;
        this.sY = e.layerY;
    }
}

The code is working, but since my circles are too small, while I am dragging it, if I am too fast or cursor leaves the circle, it stops dragging. When I return to hover the circle, it continues to drag. How can I solve this issue?

CodePudding user response:

When I move mousemove event from circle itself to main SVG element, the problem I've mentioned is solved.

component.html

<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" (mouseleave)="leave()" (mousemove)="move($event)">
    <circle *ngFor="let d of drawings" r="3" fill="red" [attr.cx]="d.x" [attr.cy]="d.y" (mousedown)="down($event, d)" (mouseup)="up()"></circle>
</svg>
  • Related