首页 > 解决方案 > 为什么这个 SVG 路径在 Firefox 上显示不正确的宽度和高度?

问题描述

我是 D3 和 SVG 的新手,并尝试在 OSX Firefox 61.0.2 上使用 SVG 路径绘制自定义形状,这是下面的代码

var svg = d3.select("body")
  .append("svg")
  .attr("width", 1800)
  .attr("height", 600)

function drawCandle(x, y, width, upper, body, lower){
  var path = d3.path()
  // path.moveTo(x + width/2, y)
  // path.lineTo(x + width/2, y + upper + body + lower)
  path.moveTo(x, y + upper)
  path.lineTo(x + width, y + upper)
  path.closePath()
  return path
}

var p = svg.append('path')
console.log(p.style('stroke-width'))

p.attr('d', drawCandle(200,100,20, 50, 100, 80))

在开发人员工具中检查时生成的路径如下所示

<svg width="1800" height="600"><path d="M200,150L220,150Z"></path></svg>

但是,如果我要在元素上使用 Inspector 悬停,它会显示宽度为 24 x 4 在此处输入图像描述

我在这里错过了什么吗?这不应该是 20 x 1 我的 CSS 目前是

path{
  stroke: blue;
  shape-rendering:crispEdges;
}

标签: d3.jssvgstroke

解决方案


你是这个意思吗?(假设 x,y 是蜡烛的左上角):

path.moveTo(x, y);
  path.lineTo(x + width, y);
  path.lineTo(x + width, y + upper);
  path.lineTo(x, y + upper);
  path.closePath();

http://jsfiddle.net/ibowankenobi/ozd10hq9/

此外,您观察到的差异是因为开发人员工具的 DOM rect 取决于供应商,Firefox 添加了笔画宽度,而 chrome 没有。在引擎盖下,客户端 rect 在两者中都是正确的,您可以验证是否这样做:

console.log(p.node().getBBox());//SVGRect { x: 200, y: 100, width: 20, height: 30 }

http://jsfiddle.net/ibowankenobi/k0t4pfjz/


推荐阅读