将SVG定位在浏览器窗口的中间

Positioning SVG at middle of browser window

本文关键字:窗口 中间 浏览器 SVG 定位      更新时间:2023-09-26

我有以下SVG定义,即使我指定了viewBox坐标,我似乎也无法将SVG窗口定位在屏幕的正中央。

var width = 1000, height = 500;
var svg = d3.select("body").append("svg")
            .attr("width", width)
            .attr("height", height);
svg.append("defs").selectAll("marker")
            .data(["suit", "licensing", "resolved"])
            .enter().append("marker")
            .attr("id", function (d) {
                return d;
            })
            .attr("viewBox", "100 -100 1000 500")
            .attr("preserveAspectRatio", "xMidYMid meet")
            .attr("display", "block")            
            .attr("refX", 25)
            .attr("refY", 0)
            .attr("markerWidth", 6)
            .attr("markerHeight", 6)
            .attr("orient", "auto")
            .append("path")
            .attr("d", "M0,-5L10,0L0,5 L10,0 L0, -5")
            .style("stroke", "#4679BD")
            .style("opacity", "0.6");

如何将SVG定位在浏览器窗口的中心位置?

如果您试图创建一个SVG元素并将其放在页面的中心,那么我想这将是一个简单的DOM节点的中心问题。但首先必须检索SVG DOM节点,它与svg变量不同。

使用此处描述的技术:https://davidwalsh.name/css-vertical-center

svgElement = document.getElementsByTagName("svg")[0];
svgElement.style.position = "relative";
svgElement.style.top = "50%";
svgElement.style.left = "50%";
svgElement.style.transform = "translate(-50%, -50%)";

演示:http://jsfiddle.net/cgupL5mk/