KahunaCoder
KahunaCoder

Reputation: 615

How do I compensate for the extra pixels added by stroke-linecap="round" in my calculated arc?

I'm creating an arc based on sunrise and sunset using the following example of a sunrise at 6:15am

hour * 15 = 90
minutes  * 0.25 = 3.75
hour + minutes = 93.75

Here is the function I used to calculate the path.

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 = this.polarToCartesian(x, y, radius, endAngle)
  var end = this.polarToCartesian(x, y, radius, startAngle)

  var largeArcFlag = endAngle - startAngle <= 180 ? '0' : '1'

  var d = [
    'M', start.x, start.y,
    'A', radius, radius, 0, largeArcFlag, 0, end.x, end.y
  ].join(' ')
  return d
}

And here is the svg snippet

<path id="sun_ring_start" :d="getArcs(27, 93.75, 0)" fill="none" stroke="yellow" stroke-width="3" stroke-linecap="round" />

If I use stroke-linecap="butt" with stroke-width="3" you can see the arc starts at 6:15 on my clock face. When I set the stroke-linecap="round" with stroke-width="3" the arc starts earlier then 6:15 because of the extra pixels added by stroke-linecap="round".

How can I compensate for the extra pixels added by stroke-linecap="round"?

Upvotes: 1

Views: 455

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101820

Work out what the round cap radius (half the line width) corresponds to in degrees. Then add or subract it from your start/end angle as appropriate.

var strokeWidth = 3;
var capSizeInDegrees = (strokeWidth/2) * 360 / cirumference.

It won't necessarily be exact, but it should be near enough for your needs.

Upvotes: 0

Related Questions