0

我正在使用 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;

谢谢!

4

1 回答 1

1

在您提供的帖子之上需要进行一些调整。

解决您的问题的一般想法是:

  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",因为它是此解决方案的主要技巧。

于 2015-04-07T13:58:38.623 回答