JS: roundRect

inspired by: http://felixniklas.com/dimensions/ more at: https://github.com/component/rounded-rect

by abhishek_soni

HTML

<canvas></canvas>

JavaScript

var roundRect = function(ctx, x, y, w, h, r) {
  var x2 = x + w;
  var y2 = y + h;

  if (w < 2 * r) r = w / 2;
  if (h < 2 * r) r = h / 2;

  ctx.beginPath();
  ctx.moveTo(x + r, y);
  ctx.arcTo(x2, y, x2, y2, r);
  ctx.arcTo(x2, y2, x, y2, r);
  ctx.arcTo(x, y2, x, y, r);
  ctx.arcTo(x, y, x2, y, r);
};

var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');

context.save();
roundRect(context, 0, 0, 50, 60, 20);
context.fillStyle = 'red'; // This should work, but it doesn't 
context.fill();
context.restore();

context.fillStyle = 'green';
context.fillText('Hey', 50, 80) // if I change this to 50 it hides behind the arc, which I don't want.
context.textAlign = "center";
context.fill();

context.save();
roundRect(context, 100, 100, 50, 90, 20);
context.fillStyle = 'red'; // This should work, but it doesn't 
context.fill();
context.restore();

context.fillStyle = 'green';
context.fillText('Hey', 90, 100) // if I change this to 50 it hides behind the arc, which I don't want.
context.textAlign = "center";
context.fill();

context.save();
roundRect(context, 300, 100, 50, 120, 20);
context.fillStyle = 'red'; // This should work, but it doesn't 
context.fill();
context.restore();

context.fillStyle = 'green';
context.fillText('Hey', 90, 130) // if I change this to 50 it hides behind the arc, which I don't want.
context.textAlign = "center";
context.fill();