首页 > 解决方案 > 如何为svg着色:标记线的颜色

问题描述

我有以下用于生成箭头线的 ng 模板:

<ng-template #linkTemplate let-link>
            <svg:g class="edge">
                <svg:marker id="arrow" viewBox="0 -5 10 10" refX="8" refY="0" markerWidth="4" markerHeight="4"
                    orient="auto">
                    <svg:path d="M0,-5L10,0L0,5" class="arrow-head" />
                </svg:marker>
                <svg:path class="line" [attr.stroke]="link.color" stroke-width="2" marker-end="url(#arrow)">
                </svg:path>                    
            </svg:g>
        </ng-template>

如何将箭头着色为 link.color 变量中指定的颜色?

标签: cssangularsvg

解决方案


诀窍是为箭头定义两个模板并相应地从行路径引用。

<ng-template #linkTemplate let-link>
                <svg:g class="edge">
                    <svg:marker id="arrow" viewBox="0 -5 10 10" refX="8" refY="0" markerWidth="4" markerHeight="4" orient="auto">
                        <svg:path d="M0,-5L10,0L0,5" class="arrow-head" />
                    </svg:marker>
                    <svg:marker id="arrow-sel" viewBox="0 -5 10 10" refX="8" refY="0" markerWidth="4" markerHeight="4" orient="auto">
                        <svg:path d="M0,-5L10,0L0,5" class="arrow-head-sel" />
                    </svg:marker>
                    <svg:path class="line" [attr.stroke]="link.color" stroke-width="2" [attr.marker-end]="link.color === undefined ? 'url(#arrow)' : 'url(#arrow-sel)'">
                    </svg:path>           
                </svg:g>
            </ng-template>

推荐阅读