How to make accurate rounded corners using HTML5 canvas?

HTML5 canvas rounded corners

CanvasRenderingContext2D.prototype.roundedRect = function(x, y, width, height, radius) {
  // Because the function is added to the context prototype
  // the 'this' variable is actually the context
  // Save the existing state of the canvas so that it can be restored later
  this.save();
  // Translate to the given X/Y coordinates
  this.translate(x, y);

  // Move to the center of the top horizontal line
  this.moveTo(width / 2, 0);

  // Draw the rounded corners. The connecting lines in between them are drawn automatically
  this.arcTo(width, 0, width, height, Math.min(height / 2, radius));
  this.arcTo(width, height, 0, height, Math.min(width / 2, radius));
  this.arcTo(0, height, 0, 0, Math.min(height / 2, radius));
  this.arcTo(0, 0, radius, 0, Math.min(width / 2, radius));

  // Draw a line back to the start coordinates
  this.lineTo(width / 2, 0);

  // Restore the state of the canvas to as it was before the save()
  this.restore();
}

window.onload = function() {
  // And you use it like this. First get the canvas and context as normal
  var canvas = document.getElementById('myCanvas')
  var context = canvas.getContext('2d')

  // Start a path and draw a rounded rectangle. The roundedRect function can be likened to the rect function
  context.beginPath();
  context.fillStyle = 'green';
  context.roundedRect(5, 5, 150, 50, 10);
  context.roundedRect(5, 60, 150, 150, 10);
  context.stroke();
  context.fill();
  context.fillStyle = 'white';
  context.textAlign = 'center';
 context.font = 'bold 12px Arial';
  context.fillText("Submit", 150 /2, 50 / 1.5);
}
DEMO
How to make accurate rounded corners using HTML5 canvas? How to make accurate rounded corners using HTML5 canvas? Reviewed by Bhaumik Patel on 7:48 PM Rating: 5