簡體   English   中英

如何將svg對象(使用DOMParser從字符串創建)添加到div元素中?

[英]How to add a svg-object (created with DOMParser from a string) into a div element?

我在這里運行Firefox 41。

我有一個完整的svg文件的代碼,只是從wikimedia的公共站點中隨機獲取的。 https://upload.wikimedia.org/wikipedia/commons/c/c6/%2212_World_fly.svg

然后,我嘗試了以下兩個版本將其推入div元素中,一次使用div的innerHTML,一次通過嘗試div的appendChild。

innerHTML至少可以工作,盡管用webdeveloper查看生成的html看起來有些懷疑

<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 15.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

也出現了。

使用appendChild根本不起作用。

我想使用諸如appendChild之類的東西,因為我知道使用innerHTML的解析器時可能會有陷阱。

那么,如何將svg文件的完整字符串放入div?

<html>
<head>
  <script type="application/javascript">
 function dgebi(id) {
    return document.getElementById(id);
}
// short svg file as string
var svgtext = ... //... here I added the string from https://upload.wikimedia.org/wikipedia/commons/c/c6/%2212_World_fly.svg
var d;
function init() {
    d = dgebi('id:testdiv');
    //useInnerHTMLToCreateSVG();
    useDOMParser();
}
function useInnerHTMLToCreateSVG() {
    d.innerHTML = svgtext;
}
function useDOMParser() {
// see https://developer.mozilla.org/de/docs/Web/API/DOMParser#Parsing_an_SVG_or_HTML_document
    var parser = new DOMParser();
    var doc = parser.parseFromString(svgtext, "image/svg+xml");
    // returns a SVGDocument, which also is a Document.
    d.appendChild(doc);
}    
function createElementSVG() {
    var se = document.createElement('SVG');
    d.appendChild(se);
    console.log(se);
}
</script>
</head>
<body onload="init();">
<div style="width:400px;height:400px;border: 1px #ff0000 solid;" id="id:testdiv"></div>
</body>
</html>

您需要附加一個元素而不是文檔,即

d.appendChild(document.adoptNode(doc.documentElement));

在實踐中,您可以省去acceptNode。 盡管它是w3c強制要求的(並且8472指出它是嚴格正確的),但瀏覽器無法訪問的站點太多,無法強制使用它。

同樣,您不能使用createElement創建SVG元素(只能創建HTML元素)。 您需要使用createElementNS即

var se = document.createElementNS('http://www.w3.org/2000/svg', 'svg');

請注意小寫名稱,因為SVG區分大小寫。

工作代碼示例:

var renderRatingReviews = function (opts) {
    var options = opts || {},
        namespace = 'http://www.w3.org/2000/svg',
        svg = document.createElementNS(namespace, 'svg'),
        circle = document.createElementNS(namespace, 'circle'),
        arc = document.createElementNS(namespace, 'path'),
        text = document.createElement('div'),
        width = options.width || 100,
        height = options.height || 100,
        radius = width / 2,
        container = options.container,
        thickness = options.thickness || 9,
        color = options.color === 'green' ? '#00B930' : options.color === 'orange' ? '#fe9d14' : options.color === 'red' ? '#ff5534' : '#00B930',
        rating = options.rating || 8,
        polarToCartesian = function (centerX, centerY, radius, angleInDegrees) {
            var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;
            return {
                x: centerX + (radius * Math.cos(angleInRadians)),
                y: centerY + (radius * Math.sin(angleInRadians))
            };
        },
        describeArc = function (x, y, radius, startAngle, endAngle) {
            var start = polarToCartesian(x, y, radius, endAngle),
                end = polarToCartesian(x, y, radius, startAngle),
                arcSweep = endAngle - startAngle <= 180 ? "0" : "1",
                d = [
                    "M", start.x, start.y,
                    "A", radius, radius, 0, arcSweep, 0, end.x, end.y
                ].join(" ");
            return d;
        },
        addSize = function (val) {
            return val;
        };
    if (container) {
        text.innerHTML = rating;
        text.className = 'text';
        svg.setAttribute('width', addSize(width));
        svg.setAttribute('height', addSize(height));
        circle.setAttribute('cy', addSize(height / 2));
        circle.setAttribute('cx', addSize(width / 2));
        circle.setAttribute('r', addSize(radius - (thickness / 2)));
        circle.setAttribute('stroke', '#e8e8e8');
        circle.setAttribute('stroke-width',  addSize(thickness));
        circle.setAttribute('fill', '#ffffff');
        arc.setAttribute('stroke', color);
        arc.setAttribute('stroke-width',  addSize(thickness));
        arc.setAttribute('fill', 'rgba(0, 0, 0, 0)');
        arc.setAttribute('stroke-linecap', 'round');
        arc.setAttribute('d', describeArc(width / 2, height / 2, addSize(radius - (thickness / 2)), 0, 359 * rating / 10));
        svg.appendChild(circle);
        svg.appendChild(arc);
        container.appendChild(svg);
        container.appendChild(text);
    }
}

renderRatingReviews({
    container: document.getElementById('elementId')
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM