raphael js rounded rectangle (another solution)

Raphael JS Rounded Rectangle - Another Solution

Creating rounded rectangles with Raphael JS can be done using the rect() method and specifying the corner radius. However, this method has a limitation since it only allows for an equal corner radius on all corners of the rectangle. Another solution is to use a combination of rect() and path methods like arc() and curveTo().

Step-by-Step Guide

  1. Create a rectangle using the rect() method with the desired dimensions.

  var paper = Raphael("paper", 200, 200);
  var rect = paper.rect(50, 50, 100, 50);
  
  1. Create four arcs using the arc() method to represent each rounded corner of the rectangle.

  var r = 10; // corner radius
  var topLeft = ["M", rect.attr("x"), rect.attr("y")+r];
  var topRight = ["M", rect.attr("x")+rect.attr("width")-r, rect.attr("y")];
  var bottomLeft = ["M", rect.attr("x")+r, rect.attr("y")+rect.attr("height")];
  var bottomRight = ["M", rect.attr("x")+rect.attr("width"), rect.attr("y")+rect.attr("height")-r];

  topLeft.push("A", r, r, 0, 0, 1, rect.attr("x")+r, rect.attr("y"));
  topRight.push("A", r, r, 0, 0, 1, rect.attr("x")+rect.attr("width"), rect.attr("y")+r);
  bottomLeft.push("A", r, r, 0, 0, 1, rect.attr("x"), rect.attr("y")+rect.attr("height")-r);
  bottomRight.push("A", r, r, 0, 0, 1, rect.attr("x")+rect.attr("width")-r, rect.attr("y")+rect.attr("height"));
  
  var path = [topLeft, topRight, bottomRight, bottomLeft];
  
  1. Create two curves using the curveTo() method to connect the arcs and complete the rounded rectangle.

  var curveTop = ["M", rect.attr("x")+r, rect.attr("y")];
  curveTop.push("Q", rect.attr("x")+rect.attr("width")/2, rect.attr("y"), rect.attr("x")+rect.attr("width")-r, rect.attr("y"));
  
  var curveBottom = ["M", rect.attr("x")+r, rect.attr("y")+rect.attr("height")];
  curveBottom.push("Q", rect.attr("x")+rect.attr("width")/2, rect.attr("y")+rect.attr("height"), rect.attr("x")+rect.attr("width")-r, rect.attr("y")+rect.attr("height"));
  
  path = path.concat([curveTop, topRight, curveBottom.reverse(), bottomLeft.reverse()]);
  
  // draw the path
  var roundedRect = paper.path(path);
  
  // remove the original rectangle
  rect.remove();
  

By using a combination of methods, we can create a rounded rectangle with different corner radius values for each corner. However, this approach can be more complicated than using the rect() method with equal corner radius values. Choose the method that works best for your project.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe