在Angular中测量svg元件的尺寸

  • 本文关键字:svg Angular 测量 angular svg
  • 更新时间 :
  • 英文 :


我正在尝试使用SVG在Angular中创建一个类似仪表的组件来绘制形状。我想把文本居中放在一个矩形内。文本将根据仪表的值而变化,因此,我想调整字体大小,使值适合矩形。或者,我可以调整数字格式(例如,如果字符串太长,则使用科学符号(,使其适合矩形。

我遇到的问题是,当我尝试测量svg元素(矩形和文本(的维度时,本地元素的getBoundingClientRect()返回零。我正在通过@ViewChild() : ElementRef获取本机元素。有更好的方法吗?

我整理了一个stackblitz,显示了在试图获取文本维度时的问题。它与我的本地副本的不同之处在于,矩形确实返回了一个维度。我使用的是Angular 5.2.11,可能是因为版本不同?编辑:我已经更新了stackblitz:https://stackblitz.com/edit/angular-oz72py

我正在下面添加app.component.ts及其html模板

import { Component,OnInit, ViewChild,ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
name = 'Angular';
@ViewChild('containerRect') containerRect : ElementRef;
@ViewChild('valueText') valueText : ElementRef;
valueStr="2512323.0";
ngOnInit()
{
console.log('container bounds:',
this.containerRect.nativeElement.getBoundingClientRect().width);
console.log('text bounds:',
this.valueText.nativeElement.getBoundingClientRect().width)
}
}

app.component.html:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120">
<svg:rect x="0" y="0" width="100%" height="100%" fill="00AA00"/>
<svg:circle cx="60" cy="60" r="60" fill="#C3002F"/>
<svg:path d="M 60 110
A 50 50 0 1 1 110 60
L 100 60
A 40 40 1 1 0 60 100
Z" 
fill="#DDDDDD" fill-opacity="1"/>
<svg:path d="M 60 110
A 50 50 0 0 1 10 60
L 20 60
A 40 40 1 0 0 60 100 
Z" 
fill="#888888" fill-opacity="1"/>
<svg:rect #containerRect x="29.090373558749814" 
y="51.717790556719336"
width="61.81925288250037"
height="16.564418886561327"
fill="#00AA00"/>
<svg:text #valueText font-size="14px" 
x="50%" text-anchor="middle"  dy="0.95em"
y="51.717790556719336">{{valueStr}}</svg:text>
</svg>

运行ngOnInit()时DOM未就绪。

相反,将代码放入ngAfterViewInit()

ngAfterViewInit()
{
console.log('container boundsx:',
this.containerRect.nativeElement.getBBox().width);
console.log('text bounds:',
this.valueText.nativeElement.getBBox().width)
}

我还建议您使用getBBox()而不是getBoundingClientRect()getBBox()方法返回以SVG为单位的值。因此,它应该更准确一点,不会受到任何缩放的影响,并且与SVG文件中的大小完全匹配。

最新更新