【发布时间】:2018-12-14 03:34:40
【问题描述】:
我想创建一个 SVG 元素,其中包含一个节点列表,每个节点都是一个矩形,里面有一个文本:
<svg class="chart" width="420" height="150" aria-labelledby="title" role="img">
<ng-container *ngFor="let item of listNode">
<g viewBox="0 0 56 18">
<rect [attr.width]="item.w" [attr.height]="2*item.h" fill="white"></rect>
<text [attr.x]="item.x" [attr.y]="item.y" text-anchor="middle" font-family="Meiryo" font-size="item.h"
fill="black">{{item.label}}</text>
</g>
</ng-container>
</svg>
但我想把文本放在矩形的中心(垂直和水平)。为此,我认为我需要在创建 SVG 元素之前测量文本的宽度。 我尝试使用以下函数来测量文本大小:
getTextWidth(text, fontSize, fontFace) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = fontSize + 'px ' + fontFace;
return context.measureText(text).width;
}
但结果不正确。 那么,有没有办法在创建真正的元素之前测量 SVG 文本元素的大小(比如我的 getTextWidth 函数),或者有没有其他方法可以创建文本正好在中心的矩形。
【问题讨论】:
-
Measuring dimensions of svg elements in Angular 的可能重复项 在画布中测量大小相当于使用
.getBoundingClientRect()- 这是错误的坐标系。 -
顺便说一句,
<g>元素没有viewBox属性 - 请改用<svg>元素。 -
你可以在测量文本后改变矩形的大小
-
this 不适合。无需测量。
标签: javascript angular svg