插入到DOM中的SVG元素被忽略(其类型被更改)

SVG element inserted into DOM is ignored (its type is changed)

本文关键字:类型 DOM 中的 SVG 元素 插入      更新时间:2023-09-26

我正在使用VivaGraph.js库来渲染SVG中的图形。我正在尝试显示一个图像裁剪成一个圆圈,为此我使用了clipPath元素-在这篇文章中推荐。然而,当我创建一个类型为大写字母的新SVG元素时,例如在我的例子中是clipPath,插入到DOM中的元素是小写的,即clippath,即使我传递给构造函数的字符串是camelCase。由于SVG区分大小写,因此忽略该元素。其他一切似乎都很好。

我还试图改变我附加子元素的顺序,希望改变'z-index',但它没有对这个产生影响。

我在函数内部使用以下代码,该函数在图中创建节点的可视化表示('addNode'回调)来创建节点:

var clipPhotoId = 'clipPhoto';
var clipPath = Viva.Graph.svg('clipPath').attr('id', clipPhotoId);
var ui = Viva.Graph.svg('g');
var photo = Viva.Graph.svg('image').attr('width', 20).attr('height', 20).link(url).attr('clip-path', 'url(#' + clipPhotoId + ')');
var photoShape = Viva.Graph.svg('circle').attr('r', 10).attr('cx', 10).attr('cy', 10);
clipPath.append(photoShape);
ui.append(clipPath);
ui.append(photo);
return ui;

谢谢!

在你提供的帖子上面需要做一些调整。

解决这个问题的基本思路是:

  1. 我们创建了一个VivaGraph svg图形(它将在dom中创建一个svg元素)
  2. 在这个svg图形中,我们只创建一次带有相对坐标的剪辑路径
  3. 当我们创建一个节点时,我们引用剪辑路径

代码是:

        var graph = Viva.Graph.graph();
        graph.addNode('a', { img : 'a.jpg' });
        graph.addNode('b', { img : 'b.jpg' });
        graph.addLink('a', 'b');
        var graphics = Viva.Graph.View.svgGraphics();
        // Create the clipPath node
        var clipPath = Viva.Graph.svg('clipPath').attr('id', 'clipCircle').attr('clipPathUnits', 'objectBoundingBox');
        var circle = Viva.Graph.svg('circle').attr('r', .5).attr('cx', .5).attr('cy', .5);
        clipPath.appendChild(circle);
        // Add the clipPath to the svg root
        graphics.getSvgRoot().appendChild(clipPath);
        graphics.node(function(node) {
               return Viva.Graph.svg('image')
                     .attr('width', 30)
                     .attr('height', 30)
                     // I refer to the same clip path for each node
                     .attr('clip-path', 'url(#clipCircle)')
                     .link(node.data.img);
            })
            .placeNode(function(nodeUI, pos){
                nodeUI.attr('x', pos.x - 15).attr('y', pos.y - 15);
            });
        var renderer = Viva.Graph.View.renderer(graph, { graphics : graphics });
        renderer.run();

dom中的结果将是这样的:

<svg>
    <g buffered-rendering="dynamic" transform="matrix(1, 0, 0,1,720,230.5)">
        <line stroke="#999" x1="-77.49251279562495" y1="-44.795726056131116" x2="6.447213894549255" y2="-56.29464520347651"></line>
        <image width="30" height="30" clip-path="url(#clipCircle)" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="a.jpg" x="-92.49251279562495" y="-59.795726056131116"></image>
        <image width="30" height="30" clip-path="url(#clipCircle)" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="b.jpg" x="-8.552786105450746" y="-71.2946452034765"></image>
    </g>
    <clipPath id="clipCircle" clipPathUnits="objectBoundingBox">
        <circle r="0.5" cx="0.5" cy="0.5"></circle>
    </clipPath>
</svg>

注意clipPathUnits="objectBoundingBox",因为它是这个解决方案的主要技巧。