动态添加的SVG不遵循剪切

时间:2018-12-20 05:48:30

标签: javascript svg

我要添加两个SVG,第二个具有较小的剪辑。但是,当添加Javascript时,它将忽略较小的剪辑。这是说明问题的Codepen:第一个是动态添加的,第二个不是。第二个有效,但第一个无效。

以下是相关代码:

$(document).ready(function() {

    $("#svgHolder").append(createSVG("field", fieldShape, "red", shieldPath));
    $("#svgHolder").append(createSVG("division", fessShape, "blue"));
});

var color = function(className, color, type) {
    $("." + className).css("fill", "#" + color);
}

var shieldPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
shieldPath.id = "fieldShield";
shieldPath.setAttribute("d", "m395,20c0.910,57.6 0.857,115 0,173-0.833,55.5-    3.60,98.8-28.5,133-29.9,40.8-79.8,70.2-144,99.2-64.2-28.9-114-58.4-144-99.2-24.9-33.9-27.6-77.2-28.5-133-0.857-57.6-0.910-115 0-173z");
shieldPath.setAttribute("style", "stroke: white; stroke-width: 3;");

var fieldShape = document.createElementNS("http://www.w3.org/2000/svg", "rect");
fieldShape.id = "fieldFill";
fieldShape.setAttribute("x", "0");
fieldShape.setAttribute("y", "0");
fieldShape.setAttribute("width", "450");
fieldShape.setAttribute("height", "450");

var fessShape = document.createElementNS("http://www.w3.org/2000/svg", "rect");
fessShape.id = "fessFill";
fessShape.setAttribute("x", "0");
fessShape.setAttribute("y", "225");
fessShape.setAttribute("width", "450");
fessShape.setAttribute("height", "225");

var createSVG = function(name, fill, color, path) {
    var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    svg.setAttribute("style", "height: 100%; width: 100%; position: absolute;");

    var clipPath = document.createElement("clipPath");
    clipPath.id = name + "Clip";
    svg.appendChild(clipPath);

    clipPath.appendChild(fill);

    if(path) svg.appendChild(path);

    var use = document.createElementNS("http://www.w3.org/2000/svg", "use");
    use.setAttribute("class", name);
    use.setAttribute("clip-path", "url('#" + clipPath.id + "')");
    use.setAttribute("href", "#fieldShield");
    use.setAttribute("fill", color);
    svg.appendChild(use);

    return svg;
}

0 个答案:

没有答案