Sign in to follow this  
wclarkson

Rounded Rectangle

Recommended Posts

I'm finding the graphics examples very impressive, but it is the simple things that are tripping me up.

I know I must be missing something simple, but is there a simple way to draw a rounded rectangle in Phaser 3?

Share this post


Link to post
Share on other sites

Not that I can find? I thought it would be a simple approach like passing in an array of points to make a polygon but it seems that it's up to the coder to use lineTo and arc to make their own rounded rect?

You can make a helper function to do it manually. Starting from the middle of one of the sides you can construct it by either defining each of the corners in order all the way around or making an array that can programmatically do that work for you if you like the functional approach. The below demos the latter but it's computationally more expensive just for the sake of being functional programming:

  this.rounded = function(x, y, width, height, radius, color) {
    if (+width < radius * 2 || +height < radius * 2) return this.add.graphics({ fillStyle: { color: color}, x: +x, y: +y})
    let options = Array.from({length: 4}, (_, index) => ({
      radians: (index * Math.PI / 2 + Math.PI) % (2 * Math.PI),
      x:  +x + (((index + 1) & 2) >> 1) * +width,
      y:  +y + ~~(index > 1) * +height,
      lx: radius * ~~((index-2) * ((index-2) & 1)),
      ly: radius * ~~-((index + 1) & 1),
      ax: radius * (~((index + 1) & 2) + 2),
      ay: radius * (~~(index < 2) || -1)
    }))

    let shape = this.add.graphics({ fillStyle: { color: color}, x: +x, y: +y})
      .beginPath()
      .moveTo(+x, +y + height >> 1)

    options.forEach((current, index, arr) => {
      shape
        .lineTo(current.x + current.lx, current.y + current.ly)
        .arc(current.x + current.ax, current.y + current.ay, +radius, current.radians, arr[index < arr.length - 1 ? index + 1 : 0].radians)
    })

    return shape
      .closePath()
      .fillPath()
  }




      let myRect = this.rounded(50, 50, 400, 200, 20, 0xff8000)

 

Share this post


Link to post
Share on other sites

Thanks! Yeah, it does seem like quite a bit for what used to be one line of code. I will take your function and try to adapt it to what I was doing. I wound up using a rectangle with two circles of the same color in the end to make a pill button. 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.