[whatwg] Canvas roundedRect

Ian Hickson ian at hixie.ch
Mon Sep 3 08:08:40 PDT 2012


On Thu, 21 Jun 2012, Igor Trindade Oliveira wrote:
>
> Currently, canvas2d does not have support for rounded rectangles and
> the web developers are implementing rounded rectangles using arcs or
> bezier curves.[1][2]

The arcTo() method is very specifically designed to enable rounded 
rectangles to be done relatively easily:

  function roundRect(c, x, y, w, h, r) {
    if (r > w/2)
      r = w/2;
    if (r > h/2)
      r = h/2;
    c.beginPath();
    c.moveTo(x+w/2, y);
    c.arcTo(x+w, y,   x+w,   y+h/2, r);
    c.arcTo(x+w, y+h, x+w/2, y+h,   r);
    c.arcTo(x,   y+h, x,     y+h/2, r);
    c.arcTo(x,   y,   x+w/2, y,     r);
    c.closePath();
    c.stroke();
  }

I don't think we need to add a feature to the API just for this.


On Thu, 21 Jun 2012, David Dailey wrote:
>
> I have seen how the <canvas> folks like to re-invent wheels

Actually we try to reuse SVG's solutions where possible.


On Thu, 21 Jun 2012, Bronislav KluÄ~Mka wrote:
>
> So why do ve have rect? 4 lines could do it... simple enough...

We have rect() mostly for historical reasons -- it was included in the API 
that Apple implemented.


> If we would go for round rect (RR), we need the obility to create RR 
> paths and the ability to create each "corner" different - specify x and 
> y radiuses for every "corner"

That's relatively easy to do as well:

  function roundRect(c, x, y, w, h, r1, r2, r3, r4) {
    // assumes that r1..r4 are in range
    c.beginPath();
    c.moveTo(x+w/2, y);
    c.arcTo(x+w, y,   x+w,   y+h/2, r1);
    c.arcTo(x+w, y+h, x+w/2, y+h,   r2);
    c.arcTo(x,   y+h, x,     y+h/2, r3);
    c.arcTo(x,   y,   x+w/2, y,     r4);
    c.closePath();
    c.stroke();
  }

Similarly if you want to do different x and y radii it's relatively easy 
to pass through to the new arcTo() method. (This isn't widely implemented 
yet so I haven't shown an example here.)

-- 
Ian Hickson               U+1047E                )\._.,--....,'``.    fL
http://ln.hixie.ch/       U+263A                /,   _.. \   _\  ;`._ ,.
Things that are impossible just take longer.   `._.-(,_..'--(,_..'`-.;.'


More information about the whatwg mailing list