我正在开发一个需要动态呈现 SVG 的企业应用程序。 SVG 用于显示平面图。 SVG 元素被描述到数据库中,并以 JSON 方式提供给前端,允许使用模板呈现图形。
我没有使用 <img>
标签,因为我必须动态更改一些属性,例如 viewBox
, 和 transform
属性。
因此我有一个架构相关的询问,我从后端获取非常大的数组(数千行),这些数组经过预处理和解析以获得适合我的组件的 JS 对象,最深层次的子数组只有一个。
该模板是 super 基础的,它包括先做一个 ngFor
循环创建 <g>
元素,然后遍历描述其他 SVG 实体(圆圈、路径、文本...)的嵌套对象
在我当前的示例中,第一个 ngFor
循环超过 800 个对象,每个后续的 ngFor
在 1 到 5 个对象之间循环。
模板渲染非常慢(大约需要 8 秒)。问题是我必须在前端重建纯 SVG。我正在使用 <defs>
和 <use>
只要有可能,但它不会减少我必须做的循环次数。
下面是模板的一部分:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="...">
<g *ngFor="let layer of layers$ | async">
<g *ngFor="let group of groups$ | async"
[attr.id]="group.id"
[attr.stroke]="group!.stroke"
[attr.stroke-width]="group!.strokeWidth"
[attr.fill]="group!.fill">
<ng-container *ngFor="let entity of groups.entities" ngSwitch]="entity.entityType">
<line *ngSwitchCase="SVG_ENTITY_TYPES.line"
[attr.x1]="entity.startPoint.x"
[attr.x2]="entity.endPoint.x"
[attr.y1]="entity.startPoint.y"
[attr.y2]="entity.endPoint.y"
[attr.stroke-width]="entity.strokeWidth" />
<path *ngSwitchCase="SVG_ENTITY_TYPES.path"
[attr.d]="entity.data" />
<!-- Other entity types -->
</ng-container>
</g>
</g>
</svg>
下面是来自数据集的示例节点,带有 "id": 42
的对象是一组。组数组包含数百个。此示例组只有一个 SVG 实体,但在实际数据集中它可能包含多个实体。
{
"id": 42,
"layerId": 1,
"fill": "black",
"stroke": null,
"strokeWidth": null,
"entities": [{
"stroke": null,
"strokeWidth": 0.1,
"entityType": 3,
"transform": {
"rotationAngle": 0.0,
"rotationCenter": null,
"translate": null,
"scaleX": 0.0,
"scaleY": 0.0
},
"attributes": {
"x1": "-2.425",
"y1": "22.527",
"x2": "-3.858",
"y2": "22.527",
"stroke-width": "0.1"
},
"startPoint": {
"x": -2.425,
"y": 22.527
},
"endPoint": {
"x": -3.858,
"y": 22.527
}
}],
"transform": {
"rotationAngle": 0.0,
"rotationCenter": null,
"translate": null,
"scaleX": 0.0,
"scaleY": 0.0
},
"attributes": {
"fill": "black"
},
"entityType": 10
}
从架构的 Angular 来看,即使我知道 Angular 不是专用于浏览器图形渲染的框架,您是否有一些架构技巧或建议来克服这一挑战?
谢谢,
最佳答案
也许您应该尝试以某种方式缓存它 - 就像使用分页(不确定我是否完全理解需要,但似乎合理您不需要同时查看 800 多个视觉对象)。
我的建议是尽可能延迟加载(一次加载 X 项),或者一次加载除显示 X 之外的所有项。
关于angular - 非常大的嵌套数组 ngFor SVG 渲染性能问题,架构问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60052468/