Hacker News new | ask | show | jobs
by c_s_guy 1568 days ago
> Though you don't need 4 arcTo in order to make a rounded rect, you can use bezier instead (we do)

I'm pretty new to this - do you have an example of using bezier? And why is it preferred over arcTo?

2 comments

You can use cubic Bézier curves to approximate a circular arc: https://pomax.github.io/bezierinfo/#circles_cubic. In many cases that's even how circular arcs are rendered, even when they are represented with a different data structure. You'll often see the the constant 0.5522... which is for quarter circles. E.g. both WPF and Java's Swing render arcs with that approximation, perhaps others, but those where the places where I checked the source code recently.

The benefit of doing this for quarter-circle arcs directly may be that you save a bunch of trigonometry that otherwise has to happen (cf. the Pomax link).

i think you'd still need 4 bezierCurveTo commands, so not sure there's any advantage over 4 arcTo:

    function roundedRect(ctx, x, y, width, height, radius) {
      ctx.beginPath();
      ctx.moveTo(x, y + radius);
      ctx.arcTo(x, y + height, x + radius, y + height, radius);
      ctx.arcTo(x + width, y + height, x + width, y + height - radius, radius);
      ctx.arcTo(x + width, y, x + width - radius, y, radius);
      ctx.arcTo(x, y, x, y + radius, radius);
      ctx.stroke();
    }
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/...