PirateApp
PirateApp

Reputation: 6194

Why is this SVG Path showing incorrect width and height on Firefox?

I am new to D3 and SVG and trying to draw a custom shape using SVG path on OSX Firefox 61.0.2 and this is the code below

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))

The generated Path when inspected in the developer tools looks like this

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

If I were to however hover using the Inspector on the element, it shows the width as 24 x 4 enter image description here

Am I missing something here? Shouldnt this be 20 x 1 My CSS currently is

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

Upvotes: 0

Views: 998

Answers (2)

Alex W
Alex W

Reputation: 38173

It looks like it's related to the way stroke-miterlimit is being used to calculate the dimensions. When changing stroke-miterlimit to 1 it adjusts the height from 4 to 1.45001

MDN

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))
path{
  stroke: blue;
  stroke-width:1px;
  stroke-miterlimit: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.5.0/d3.js"></script>

Upvotes: 1

ibrahim tanyalcin
ibrahim tanyalcin

Reputation: 6491

Did you mean this? (supposing x,y is the top left corner of the candle):

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/

Also the difference you observe because developer tool's DOM rect is vendor dependent, Firefox adds the stroke-width, chrome does not. Under the hood, the client rect is correct in both, you can verify if you do:

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

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

Upvotes: 1

Related Questions