Home > Enterprise >  SVG: layering of objects regarding events
SVG: layering of objects regarding events

Time:11-16

I have a problem with layering and events of a SVG.

Example at: https://stackblitz.com/edit/angular-ivy-rkxuic?file=src/app/app.component.ts

app.component.ts

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  
<svg xmlns="http://www.w3.org/2000/svg" height="400px" width="400px">
  <rect x="30" y="30" width="100" height="100" fill="grey" (mouseenter)="txtg='in grey'" (mouseleave)="txtg=''" />
  <rect x="70" y="70" width="50" height="50" fill="yellow"  
      (click)="txty='yellow clicked'" (mouseleave)="txty=''" pointer-events="all"/>
</svg>
<p>
txtg: {{txtg}}<br/>
txty: {{txty}}
  
  `,
})
export class AppComponent {
  txtg: string = '';
  txty: string = '';
}

  • Even if I am in YELLOW I want to be in GREY because YELLOW is inside GREY. So from the perspective of hovering GREY should be in the foreground but with YELLOW viewable.

  • But I want to be able to click YELLOW too - so for that YELLOW shoult be in the foreground.

Is there a way I get both?

CodePudding user response:

The two rects are siblings, so you can't bubble up the event.

Either you replicate the mouseenter event on the yellow rect:

<svg xmlns="http://www.w3.org/2000/svg" height="400px" width="400px">
    <rect x="30" y="30" width="100" height="100" fill="grey" 
        (mouseenter)="txtg='in grey'" 
        (mouseleave)="txtg=''" 
    />
    <rect x="70" y="70" width="50" height="50" fill="yellow" 
        (mouseenter)="txtg='in grey'"
        (click)="txty='yellow clicked'" 
        (mouseleave)="txty=''"
    />
</svg>

Or you enclose both in a g and set the mouseenter and mouseleave events on that:

<svg xmlns="http://www.w3.org/2000/svg" height="400px" width="400px">

    <g (mouseenter)="txtg='in grey'" (mouseleave)="txtg=''">
        <rect x="30" y="30" width="100" height="100" fill="grey" />
        <rect x="70" y="70" width="50" height="50" fill="yellow"
            (click)="txty='yellow clicked'" 
            (mouseleave)="txty=''" 
            pointer-events="all"
        />
    </g>
</svg>
  • Related