)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Parametric Equation for Rectangle

  1. // from http://math.stackexchange.com/questions/69099/equation-of-a-rectangle
  2. const rect = (px, py, rx, ry, t) => ({
  3.   x: px + rx + rx * (Math.abs(Math.cos(t)) * Math.cos(t) + Math.abs(Math.sin(t)) * Math.sin(t)),
  4.   y: py + ry + ry * (Math.abs(Math.cos(t)) * Math.cos(t) - Math.abs(Math.sin(t)) * Math.sin(t))
  5. })
  6.  
  7. const SIZE = 200
  8.  
  9. const c = document.body.appendChild(
  10.   Object.assign(document.createElement`canvas`,
  11.     { width: SIZE, height: SIZE }
  12.   )).getContext`2d`
  13.  
  14. c.fillStyle = 'black'
  15. c.fillRect(0, 0, SIZE, SIZE)
  16.  
  17. let t = 0
  18. setInterval(() => {
  19.   const { x, y } = rect(20, 20, 60, 70, t)
  20.   c.fillStyle = 'rgba(255, 0, 0, .1)'
  21.   c.fillRect(x, y, 10, 10)
  22.   t += .05
  23. }, 16)

Wanted to know how to do this for something back in 2015. Great math stackexchange answer here: http://math.stackexchange.com/questions/69099/equation-of-a-rectangle

Could be optimized but leaving as is to match:

x = p(|cos t|cos t + |sin t| sin t)
y = p(|cos t|cos t - |sin t| sin t)

One small change here is to add the width and height to the offset so that it draws from the upper left hand corner instead of the center…

snippet.zone ~ 2021-24 /// {s/z}