Thursday, July 29, 2010

Canvas Rounded Corner Rectangles

I've recently started using the canvas tag and  needed to draw rounded corner rectangles. I did find a good post explaing how to do it but I didn't find a nice method so I decided to create one.  I took Futomi Hatano's code  and abstracted it into a method.

/**
 * Draws a rounded rectangle using the current state of the canvas. 
 * If you omit the last three params, it will draw a rectangle 
 * outline with a 5 pixel border radius 
 * @param {CanvasRenderingContext2D} ctx
 * @param {Number} x The top left x coordinate
 * @param {Number} y The top left y coordinate 
 * @param {Number} width The width of the rectangle 
 * @param {Number} height The height of the rectangle
 * @param {Number} radius The corner radius. Defaults to 5;
 * @param {Boolean} fill Whether to fill the rectangle. Defaults to false.
 * @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true.
 */
function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
  if (typeof stroke == "undefined" ) {
    stroke = true;
  }
  if (typeof radius === "undefined") {
    radius = 5;
  }
  ctx.beginPath();
  ctx.moveTo(x + radius, y);
  ctx.lineTo(x + width - radius, y);
  ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  ctx.lineTo(x + width, y + height - radius);
  ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  ctx.lineTo(x + radius, y + height);
  ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  ctx.lineTo(x, y + radius);
  ctx.quadraticCurveTo(x, y, x + radius, y);
  ctx.closePath();
  if (stroke) {
    ctx.stroke();
  }
  if (fill) {
    ctx.fill();
  }        
}

And it can be used like the following:

// My html contains a canvas with id "rounded-rect" 500X350
var ctx = document.getElementById("rounded-rect").getContext("2d");
// Draw using default border radius, 
// stroke it but no fill (function's default values)
roundRect(ctx, 5, 5, 50, 50);
// To change the color on the rectangle, just manipulate the context
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.fillStyle = "rgba(255, 255, 0, .5)";
roundRect(ctx, 100, 5, 100, 100, 20, true);
// Manipulate it again
ctx.strokeStyle = "#2d6";
ctx.fillStyle = "#abc";
roundRect(ctx, 100, 200, 200, 100, 50, true);

Which will produce the following output:




For Firefox and Chrome (and maybe other browsers), you can do the following for syntactic sugar

CanvasRenderingContext2D.prototype.roundRect = 

function(x, y, width, height, radius, fill, stroke) {
  if (typeof stroke == "undefined" ) {
    stroke = true;
  }
  if (typeof radius === "undefined") {
    radius = 5;
  }
  this.beginPath();
  this.moveTo(x + radius, y);
  this.lineTo(x + width - radius, y);
  this.quadraticCurveTo(x + width, y, x + width, y + radius);
  this.lineTo(x + width, y + height - radius);
  this.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  this.lineTo(x + radius, y + height);
  this.quadraticCurveTo(x, y + height, x, y + height - radius);
  this.lineTo(x, y + radius);
  this.quadraticCurveTo(x, y, x + radius, y);
  this.closePath();
  if (stroke) {
    this.stroke();
  }
  if (fill) {
    this.fill();
  }        
}

// Now you can just call
var ctx = document.getElementById("rounded-rect").getContext("2d");
ctx.roundRect(5, 5, 50, 50);

Here's a JsFiddle that you can edit freely

99 comments:

  1. Yay Juan! Good job! Gotta say, big bro, I don't understand a thing, but I came to show my love. Hahaha!
    Kiss kiss from your sis,

    ReplyDelete
  2. Hi,

    nice Idea, but isnt it possible to inherit your own Context class from canvas Context? So that you dont need to pass the context? Would be more elegant or?
    BTW. can i use the code for an Palm Web OS project i am working on?

    ReplyDelete
  3. @Matthias: Please do use it for anything you'd like. I don't think there's a way to inherit or augment the CanvasContext object returned by getContext() that works across browsers. Let me know if you know how to do it. I modified the post to show you how to do what you want in Firefox. By the way, thanks for the first comment on my blog that is not from a relative :)

    I knew I should have added a disclaimer. This is not the code I actually use in production. This is just the simplest way to do it so that others can benefit.

    ReplyDelete
  4. There's a bug on line 15 of the first listing:

    stroke = stroke === undefined ? true : false;

    should be

    stroke = stroke === (undefined || true) ? true : false

    ReplyDelete
  5. Thanks Brian. Fixed it with a clearer syntax.

    ReplyDelete
  6. Thanks! I've used your routine on my page: http://dbp-consulting.com/depthoffocus.html I changed a couple of things, I added ctx.save() at the beginning and ctx.restore() at the end, and switched the order of the stroke and fill at the end, since if you did both, the fill messed up the stroke a bit. In a comment in the routine, I give you credit, and have a link back to this blog.

    ReplyDelete
  7. Well the url for my page is different. It's:
    http://dbp-consulting.com/Photography/CircleOfConfusion.html
    I also made it so you can have an additional boolean arguments for the top left, top right, bottom right and bottom left corners. For each of the arguments, if specified as true, that corner will be rectangular. If unspecified it works just like yours.

    I have:
    var tl=arguments[7];
    var tr=arguments[8];
    var br=arguments[9];
    var bl=arguments[10];
    and then for each corner a section like:

    if(!tr){
    this.quadraticCurveTo(x+width,y,x+width,y+radius);
    }else{
    this.lineTo(x+width,y);
    this.lineTo(x+width,y+radius);
    }

    That way, if you don't specify them the test as false and you get the original specification. As an example of how I used that, look at the colored header on the CoC widget. I wanted to draw it so that the corners would match the canvas, and now I can by adding the correct arguments.

    ReplyDelete
  8. Hi Patrick, thanks for the link to to your usage, it's nice to see someone using it. I'll add your changes (support for multiple corner radii) to this post soon. Thanks for the link back. I should add a note explaining that all code I post here is free for the taking and any link backs are done out of generosity, they are not required.

    Nice job implementing dragging within the canvas tag. I've had to do it myself and it's a PITA.

    ReplyDelete
  9. You must be talking about the sliders I made. I have some really cool buttons too. I made a generic handler for events so that javascript objects could register for events and provide a hit() routine. When an event comes in for the canvas, it looks through the queue for that event and calls the hit() routine for each thing passing the x,y in canvas coordinates for the event. If hit returns true, the callback for the object gets called with the event. I figured that way complex graphic shapes could all use this, and each would be the expert on whether the event hit them. Once the framework was set up adding sliders and buttons et.al. turned out to be really easy. If you haven't checked out my site in a while (dbp-consulting.com) check it out, and look at the tutorials.

    ReplyDelete
  10. good work !
    I made a live example using this code at http://jsfiddle.net/d4JJ8/4/

    ReplyDelete
  11. Thanks for this...helped and works very well

    ReplyDelete
  12. just for the js challenged folks (like myself) that might stumble on this - I struggled with the the contextual call version - your "syntactical sugar" version - not working for the longest time. Finally decided to move the function definition in the js file above the location in the file where I get the context object and magically it started working! Not sure if that is browser specific behavior but I was getting the same behavior on both chrome and safari on mac - btw that approach does work on safari (at least the version I have (5.1.2) )

    ReplyDelete
  13. Great function. Can I use it in an open source data visualization library?
    https://github.com/bengarvey/evidensity.js/

    ReplyDelete
    Replies
    1. Cool stuff, feel free to use it, attribution not required, but appreciated. Love the name of your lib

      Delete
  14. Hi I am using this wpaint code in my application, but the save image options is not working after I merge the code in my application, can you please help me by giving the required changes for save image option to work. thanks in advance for your help :)

    ReplyDelete
    Replies
    1. Somu, I'm not sure why you think I can help with wPaint. You should ask at http://stackoverflow.com/

      Delete
  15. Amazing write up, never read such an informative blog and enjoyed it. Thankyou. Keep up the good work. Looking forward to read more.

    Housely
    home decor
    best home interior design

    ReplyDelete
  16. Site Analysis Tool - How to know the website is SEO friendly or not? SiteAnalysisTool.com is an online website analysis tool & free analysis tools. The site analysis tool is a very simple & fast SEO analysis tool for website performance.
    free website analysis
    website analysis

    ReplyDelete
  17. At Infotrench SEO Company - Innovation, quality, creativity, and promptness are the main mantras of Infotrench Technologies and we imbibe these mantras in our work, to the core.
    Digital Marketing Company in Bhopal
    Search Engine Optimization Company in Bhopal

    ReplyDelete
  18. I really like your post. Great amazing things here. I am very satisfied to see your post. Thanks so much and I'm looking
    hair accessories for women
    cute hair bands

    ReplyDelete
  19. Mmm.. estimable to be here in your report or notify, whatever, I repute I should moreover process strong for my have website want I play some salubrious further updated busy in your location. bitcoin converter widget

    ReplyDelete
  20. I blog quite often and I truly appreciate your content. The article has truly peaked my interest. I'm going to bookmark your website and keep checking for new details about once a week. I opted in for your RSS feed as well. Kaun Banega Crorepati Lottery Winner

    ReplyDelete
  21. Read about best smartphone news reviews, price and specifications and much more features
    Done
    Done
    Done
    Done

    ReplyDelete
  22. Once you purchase your Roku streaming media player, be it a Roku Express or a Roku Ultra, you need to activate it before you can stream content on it. Therefore, in order to activate Roku using roku.com/link, you will need an activation code that is generated by your TV connected to the Roku device. If at all you need assistance in this setup process, just give us a call at our toll-free number +1-805-259-3373.

    ReplyDelete
  23. provides the best services to customer related to protect the mobile from theft through Track Lost Phone in USA, How to How to track a Phone with imei number in USA,imei tracker online, imei tracker in USA,

    ReplyDelete
  24. Superb blog! thank you so much for sharing this informative post. Truly being among the best security stages where you can purchase items at solid costs. This is extremely one of the first-class antivirus programming accessible in the market.
    mcafee.com/activate | mcafee login | install mcafee with activation code

    ReplyDelete
  25. Your blog is very creative and uefull…rokucomlink1.sitey.me is the free official site to link, activate, set-up and manage your Roku player or Roku TV. Roku never charges for linking or set-up support.
    roku activation link

    ReplyDelete
  26. When you visit an iPhone app development company with or without an app idea, you’ll be amazed to seek out that your business can get a plethora of advantages with a totally functional, futuristic app.
    web development company
    digital marketing company

    ReplyDelete
  27. Get Hulu activate at hulu.com/activate or visit at www.hulu.com/activate for making your hulu activation process easy.For More visit Hulu Activation code.
    Hulu.com/Activate
    www.Hulu.com/Activate

    ReplyDelete
  28. Merely installing Webroot SecureAnywhere does not guarantee safety for the system. To avail the complete security of Webroot SecureAnywhere, you need to activate it as well. You can do so with the help of the keycode.
    www.webroot.com/safe
    webroot.com/safe
    webroot safe

    ReplyDelete
  29. McAfee Total Protection is concerned, it will automatically run the Vulnerability Scanner on a specific date. You can even create a schedule and then choose to run the scan every week, every alternate week, or on a monthly basis, as per your choice. For more information visit our website! https://mcafeepro.com/

    ReplyDelete
  30. CodeIgniter Development is the most appropriate MVC framework for high-performance web applications development, favouring simple solutions, avoid complexity, and inspiring coding norms. This is a powerful Strategy of php and want to hire codeigniter developer with empower your business till web development process with php codes which can be possible by codeigniter development company as a strong and open source php framework.

    ReplyDelete
  31. QuickBooks Support 24*7 work for the best outcome for there users, if you have any trouble regarding not to worried just talk to Our QuickBooks experts.Dial +1-855-533-6333 QuickBooks Support Phone Number

    ReplyDelete
  32. awesome content you have shared on your blog
    you can check our GYC silicon straps high quality printing premium looking bands straps compatible for Mi Xiomi BAND 3 BAND 4. Click on the link given below

    CLICK HERE
    CLICK HERE
    CLICK HERE
    CLICK HERE

    ReplyDelete
  33. I read a lot of blog posts and I never heard of such a topic. I love the subject you have done about bloggers. Very simple. I am also writing a blog related to the best visa consultants, process and application. You can also see this.
    Visa Consultant in Delhi

    ReplyDelete
  34. I read a lot of blog posts and I never heard of such a topic. I love the subject you have done about bloggers. Very simple. I am also writing a blog related to the best canada PR visa consultants process and application. You can also see this.

    ReplyDelete
  35. Thanks for sharing great content with us. I like reading your site's content more. I appreciate your writing skills and the way you are written. I am also a content writer and writing about a Malta work permit, please check and review that.

    ReplyDelete
  36. Good resource. bsc 3rd year time table The best part is that you keep it updating.

    ReplyDelete
  37. Hey ,

    Great Job . You Know what ?

    I read a lot of blog posts and I never heard of such a topic. I love the subject you have done about bloggers. Very simple. I am also writing a blog related to the malta work permit. You can also see this.

    ReplyDelete
  38. What a fantastic post! This is so chock full if useful information I can't wait to dig deep and start utilizing the resources you have given me. your exuberance is refreshing

    you've outdone yourself this time

    This is probably the best, most concise step by step guide i've evere seen on how to build a successful blog. i am also writing blog about the kindly review it online english speaking classes for kids.

    ReplyDelete
  39. What an awesome post! This is so crammed with helpful data I can hardly wait to burrow profound and begin using the assets you have given me. your abundance is invigorating

    you've done something extraordinary for yourself this time

    This is presumably the awesome, brief bit by bit direct I've at any point seen on the most proficient method to construct a fruitful blog. I'm likewise composing blog about the kindly audit it. french language institute in delhi .

    ReplyDelete
  40. Unable to solve Kindle won’t connect to wifi error? Don’t worry, you can get connected with our experts to get the quick solution to solve this error. We are available 24/7 to help you. So you can contact us anytime whenever you want help with your kindle device. To know more visit the website Ebook Helpline.

    ReplyDelete
  41. How to solve a canon printer won't connect to wifi? Get connected with us. We are one of the most reliable, and independent service providers, providing 24/7 online services for printers at a very nominal charge. To know more visit the website Printer Offline Error.

    ReplyDelete
  42. Very nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed browsing your blog posts In any case I’ll be subscribing to your feed and I

    hope you write again very soon good suggestions about blogging thanks a lot you give nice information
    amazon.com/mytv
    primevideo.com/mytv
    amazon.com/mytv login
    amazon.com/mytv
    amazon.com mytv

    ReplyDelete
  43. Very nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed browsing your blog posts In any case I’ll be subscribing to your feed and I

    hope you write again very soon good suggestions about blogging thanks a lot you give nice information
    amazon.com/mytv
    amazon.com/mytv
    www.amazon.com/mytv
    amazon.com/mytv
    amazon.com/mytv

    ReplyDelete
  44. Printing is not always smooth and at times during the work, you may be faced with annoying technical failures. Canon Printer Offline Error, including its many problems, makes you drive up the wall when you stop doing the printing work. Somehow it is a common problem, but luckily it can be exterminated. However, the first user should know some common root causes for this error before turning Canon printers online offline.
    Visit For more info: Canon Printer Offline

    ReplyDelete
  45. Are you going to face any issues regarding how to Reset Orbi Router Password? Then consult with our experienced experts. They have the tools as well as the knowledge to see the issue and then resolve it. To get instant 24*7 help, feel free to contact us at USA/CA: +1-855-869-7373 and UK/London: +44-800-041-8324.

    ReplyDelete
  46. Canon manufacturer site ij.start.canon is the platform to get the Canon printer software where you can download the latest printer drivers to start your Canon model for printing, scanning, faxing, copying documents, and more
    canon.com/ijsetup | ij.start canon | ij.start.canon | http://ij.start.canon | https://ij.start.canon


    ReplyDelete
  47. 메이저놀이터 목록 신재은누드사진 스포츠분석추천 챔스일정 메시 호날두 사다리사이트 승인전화없는메이저사이트 다잡아 사설토토추천 빅카지노
    I recommend a Toto site that has been verified for safe use. 토토사이트 If you ask VIP Toto, I promise to recommend a safety playground. 안전토토사이트We promise to recommend the Toto site that is safer than anyone else, 토토 and please contact VIP Toto for a major safety playground that you can trust and use. 스포츠토토

    ReplyDelete
  48. Are you facing issues on How to Install Panda Antivirus? Are you getting irritated? Do not worry, there is nothing to be worried for. You can visit our official website antivirus activation helpline. If you are not able to fix this issue, call our experts on toll-free helpline numbers at USA/CA: +1-855-869-7373 and UK/London: +44-800-041-8324. Here our experts will help to resolve your problems.

    ReplyDelete
  49. fferent devices.Open your browser

    Type Norton com setup sign in or the URL
    Sign in to your Norton setup account

    Hit on the download button

    Check the license agreement before clicking the download

    Select the option per your browser

    Tap on the ‘Run’ icon

    Now, the account control window opens

    Click on continue





    norton.com/setup
    www.norton.com/setup
    norton setup

    ReplyDelete
  50. Nice content thank for sharing the valuable info with Us. Are you looking to download/install Brother printer drivers on the Operating system Windows 10 or Mac have any trouble can connect www.brother-support.us can help better.

    ReplyDelete
  51. Nice content thanks for sharing with us. for Canon printer won't print Make sure there is paper in the tray(s), check the ink or toner cartridges aren't empty, the USB cable is plugged in or the printer is connected to Wi-Fi. And if it is a network or wireless printer, try using a USB cable instead.

    ReplyDelete
  52. Know the best method to resolve the Brother Printer Offline Mac issue with the help of Printer Offline Tech. If you want to know how to fix these issues, then you can call us on our toll-free numbers at USA/CA: +1-888-966-6097 and UK/London: +44-808-169-7737. Our experts are the professionals who will make sure they help you in fixing your brother Printer issues.

    ReplyDelete
  53. You're so interesting! I don't suppose I've read anything like this before.
    So great to find someone with a few unique thoughts on this issue.
    Seriously.. many thanks for starting this up. This site is something that is needed on
    the internet, someone with some originality!부산오피

    ReplyDelete
  54. "mcafee is an antivirus software providers that secure your computer for virus , worms ,trojens and other mailcious program .it provides full range of
    security product like antivirus , firewall etc .you have to do mcafee antivirus download "

    ReplyDelete
  55. Nice Blog !
    Our team at QuickBooks Customer Service Number makes sure that you are 100% happy and satisfied with our work in these tumultuous times.

    ReplyDelete
  56. The Internet is full of uncountable amounts of information. Whether the information is accurate should be verified through verification, but many people search and believe it right away.토토사이트

    ReplyDelete
  57. I have joined your feed and look forward to
    seeking more of your magnificent post. Also, I’ve shared your site in my social networks! 토토사이트

    ReplyDelete
  58. I am happy to share the post.
    Your post is interesting and amazing! It is useful and helpful to me. I like it very much and look forward to hearing from you. Please visit my site and leave a comment.

    카지노사이트


    온라인카지노


    우리카지노


    온라인바카라


    바카라사이트


    라이브카지노

    ReplyDelete
  59. Youre so right. Im there with you. Your weblog is definitely worth a read if anyone comes throughout it. Im lucky I did because now Ive received a whole new view of this. 먹튀검증사이트


    ReplyDelete
  60. Hello there! Quick question that’s completely off topic.
    Do you know how to make your site mobile friendly? My website looks weird when viewing from my iphone.
    I’m trying to find a template or plugin that might
    be able to resolve this issue. If you have any recommendations, please share.
    Thank you!

    website:온라인카지노

    ReplyDelete
  61. However when it comes to promoting your business, postcards certainly don’t show their age next to their contemporaries: the text message and the email. 바카라


    ReplyDelete
  62. I truly like your thoughts on the issue. I now have an unmistakable thought on what this matter is about.. 온라인바카라


    ReplyDelete
  63. As I am looking at your writing, 우리카지노 I regret being unable to do outdoor activities due to Corona 19, and I miss my old daily life. If you also miss the daily life of those days, would you please visit my site once? My site is a site where I post about photos and daily life when I was free.


    ReplyDelete
  64. It's really great. Thank you for providing a quality article. There is something you might be interested in. Do you know 먹튀검증? If you have more questions, please come to my site and check it out!


    ReplyDelete
  65. Hi there, I simply hopped over in your website by way of StumbleUpon. Now not one thing I’d typically learn, but I favored your emotions none the less. Thank you for making something worth reading. 카지노슬롯


    ReplyDelete
  66. I saw your article well. You seem to enjoy 안전놀이터 for some reason. We can help you enjoy more fun. Welcome anytime :-)


    ReplyDelete
  67. What I was thinking about was solved thanks to your writing. I have written on my blog to express my gratitude to you.토토사이트My site is We would be grateful if you visit us.


    ReplyDelete
  68. Hello ! I am the one who writes posts on these topics크레이지슬롯 I would like to write an article based on your article. When can I ask for a review?


    ReplyDelete
  69. How can you think of this? I thought about this, but I couldn't solve it as well as you.안전놀이터I am so amazing and cool you are. I think you will help me. I hope you can help me.


    ReplyDelete
  70. Youre so right. Im there with you. Your weblog is definitely worth a read if anyone comes throughout it. Im lucky I did because now Ive received a whole new view of this. 오공슬롯"


    ReplyDelete
  71. I finally found what I was looking for! I'm so happy. 바카라사이트 Your article is what I've been looking for for a long time. I'm happy to find you like this. Could you visit my website if you have time? I'm sure you'll find a post of interest that you'll find interesting.


    ReplyDelete
  72. It's so nice to know you. I hope you also welcome me.카지노사이트검증If you welcome me, please visit my blog and write. My blog is on It's hard because of Covid - 19, but let's do our best!!


    ReplyDelete
  73. You made some good points there. I did a Google search about the topic and found most people will believe your blog. 메리트카지노


    ReplyDelete
  74. I'm so happy to finally find a post with what I want. casino You have inspired me a lot. If you are satisfied, please visit my website and leave your feedback.


    ReplyDelete
  75. Hello, I am one of the most impressed people in your article. 슬롯사이트 If possible, please visit my website as well. Thank you.


    ReplyDelete
  76. Hi....Nice Blog. If you are facing any issue in QuickBooks, dial QuickBooks Support Number in Arizona and get your problem instantly.

    ReplyDelete
  77. If you are looking to tour & Travel at the best tourist places in india! Choose one of them from Goa,
    Pondicherry, Mahabalipuram , Havelock in Andaman, Tarkarli , Kerala, Chandipur , and Lakshadweep. Buy air ticket ltd offer you cheap trip to visit in india at any time.

    List of govt. primary school in dhaka city Top Five Government Schools in Dhaka.

    ReplyDelete
  78. Looking at this article, I miss the time when I didn't wear a mask. 바카라사이트 Hopefully this corona will end soon. My blog is a blog that mainly posts pictures of daily life before Corona and landscapes at that time. If you want to remember that time again, please visit us.


    ReplyDelete
  79. https://activites.paroledemamans.com/comment-organiser-facilement-un-grand-rassemblement-familial

    ReplyDelete
  80. Very nice article please read this: https://bit.ly/3mUiKSN

    ReplyDelete
  81. I've been searching for hours on this topic and finally found your post. 바카라사이트, I have read your post and I am very impressed. We prefer your opinion and will visit this site frequently to refer to your opinion. When would you like to visit my site?


    ReplyDelete
  82. I really happy found this website eventually. Really informative and inoperative, Thanks for the post and effort! Please keep sharing more such blog.


    gemini login
    bitcoin login
    bitcoin login

    ReplyDelete

  83. Have you faced any issues regarding how to fix the Amazon Alexa App Not Working issue? Then don't worry; you can take help from our Smart Speaker Help experts. We are here to help you. To get instant help, then call us at USA: +1-872-888-1589. We are 24*7 hours for you.

    ReplyDelete
  84. Thanks for sharing – perfect tips for me as I have been planning to start my own blog.japan population

    ReplyDelete
  85. I’m very pleased to discover this site. I want to to thank you for ones time for this particularly wonderful read!! I definitely savored every part of it and i also have you saved as a favorite to see new information on your blog. 메이저놀이터


    ReplyDelete