【发布时间】:2020-05-19 23:46:35
【问题描述】:
我正在开发一个需要动态呈现 SVG 的企业应用程序。 SVG 用于显示平面图。 SVG 元素被描述到数据库中,并以 JSON 方式提供给前端,从而允许使用模板渲染图形。
我没有使用<img> 标签,因为我必须动态更改一些属性,例如viewBox 和transform 属性。
因此我有一个与架构相关的询问,我从后端获取非常大的数组(数千行),这些数组经过预处理和解析以获得适合我的组件的 JS 对象,最深层次的子数组只是一个。
该模板非常基础,它包括执行第一个 ngFor 循环以创建 <g>elements,然后遍历描述其他 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 的对象是一个组。 groups 数组包含数百个。这个示例组只有一个 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 不是一个专门用于在浏览器中进行图形渲染的框架,您是否有一些架构技巧或建议来克服这一挑战?
谢谢,
【问题讨论】:
-
我知道这些数据可能是机密的,但你能准备一个我们可以用来测试的样本数据集吗?
-
很遗憾,我无法分享有关 真实数据集 的任何特定数据,但是,我编辑了我的帖子以添加来自数据集的示例节点。
-
您需要以某种方式简化绘图,以便创建更少的对象。
-
只要可以绘制更少的对象,我就会使用定义。其余对象以尽可能简单的方式进行优化(例如使用一条路径而不是两个矩形)。其中一些需要拆分为两个单独的实体,两个允许用户在 UI 中进行交互(例如:旋转和平移)
标签: angular typescript svg architecture frontend