Edge浏览器无法正确处理SVG中的缩放和text-anchor:middle。

7
我是一名有用的助手,可以为您进行翻译。以下是您需要翻译的内容:
我正在使用D3编写一个图形显示程序,发现Microsoft Edge无法正确处理边缘缩放的问题。我的代码如下:
HTML:
<svg id="container" width="200" height="200">
  <g id="inner-container">

  </g>
</svg>

JS:

var container = d3.select("#container");
var innerContainer = container.select("g");
container.call(d3.behavior.zoom().scaleExtent([.5,4]).on("zoom", function(){
  innerContainer.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
}));

var nodes = innerContainer.append("g").selectAll(".graph-node");
var labels = innerContainer.append("g").selectAll(".graph-label");

var data = ["A", "B", "C", "D", "E"];

nodes.data(data).enter().call(function (selection){
  selection = selection.append("g");
  selection.attr("class", ".graph-node");
  selection.attr("transform", function(d, i){
    return ["translate(", (i * 20).toString(), " ", (i * 20).toString(), ")"].join("");
  });
  selection.append("rect")
    .attr("width", 20)
    .attr("height", 20)
    .attr("rx", 2).attr("ry", 2)
    .attr("fill", "red");
  selection.append("text")
    .text(function(d){ return d; })
    .attr("text-anchor", "middle")
    .attr("x", 10).attr("y", 15)
    .style("fill", "white");
});
labels.data(data).enter().call(function (selection){
  selection = selection.append("g");
  selection.attr("class", "graph-label");
  selection.append("text")
    .text(function (d) { return "Node" + d; });
  selection.attr("transform", function (d, i) {
    return ["translate(", (i * 20 + 25).toString(), " ", (i * 20 + 15).toString(), ")"].join("");
  });
});

在Google Chrome、IE和Firefox中,缩放功能完全按照预期工作。但是,当我在Microsoft Edge中运行此代码时,节点上方的文本标签将向右移动,随着缩放而完全消失,直到它们离开矩形。如果不设置text-anchor,问题就会消失,但这意味着我必须手动考虑文本定位,特别是考虑到该网站被国际使用的情况。(文本字符本身并不重要,因为它们来自最终产品中的自定义字体)。
我应该如何解决这个问题,在提供居中对齐的文本标签的同时,使其在Edge上正确显示?

在JSFiddle中查看

1个回答

0

在文本布局中,我们经常会遇到浏览器不兼容的情况。如果你找不到适用于所有浏览器的 CSS 属性组合,这里有另一种选择:

在页面中添加一个 <pre> 元素。根据定义,该元素是不可见的。使用 D3 的 select 选择该元素。将要布局的文本作为 innerHTML 添加到该元素中。使用 classedstyle 来精确地设置元素的样式,就像设置文本样式一样。现在,您可以通过浏览器函数 getComputedTextLength 或读取元素的尺寸来获取文本的准确长度。

将所有这些隐藏在一个方便的重用函数或 TextLengthCalculator 类中。

一旦您获得了尺寸,就可以自己计算所需的偏移量,并通过调整其 x 和 y 属性来简单地移动文本。

这种方法快速且考虑到本地化和样式。它甚至非常干净和可靠,因为仍然是浏览器本身进行计算。虽然浏览器在这里仍然有时会产生不同的结果,但至少每个浏览器在自己的计算中是一致的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接