我正在尝试使用 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>