【问题标题】:Measuring dimensions of svg elements in Angular在Angular中测量svg元素的尺寸
【发布时间】:2019-01-13 03:57:40
【问题描述】:

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

我遇到的问题是,当我尝试测量 svg 元素(矩形和文本)的尺寸时,本机元素的 getBoundingClientRect() 返回零。我通过@ViewChild() : ElementRef 获取本机元素。有没有更好的方法来做到这一点?

我整理了一个堆栈闪电战,它在尝试获取文本尺寸时显示了问题。它与我的本地副本的不同之处在于矩形确实返回了一个尺寸。我使用的是 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>

【问题讨论】:

  • stackblitz 链接显示了一小段文字,但似乎没有做任何其他事情。你有正确的网址吗?
  • @PaulLeBeau 我想我没有在 stackblitz 中保存示例:)。我已经保存了,链接应该可以正常使用

标签: angular svg


【解决方案1】:

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 文件中的大小完全匹配。

【讨论】:

  • 太棒了!这解决了我的问题,并开始了解 getBBox() :)
猜你喜欢
  • 2020-12-24
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
  • 1970-01-01
  • 2019-03-25
相关资源
最近更新 更多