Parametric Equation for Rectangle
// from http://math.stackexchange.com/questions/69099/equation-of-a-rectangle
const rect = (px, py, rx, ry, t) => ({
x: px + rx + rx * (Math.abs(Math.cos(t)) * Math.cos(t) + Math.abs(Math.sin(t)) * Math.sin(t)),
y: py + ry + ry * (Math.abs(Math.cos(t)) * Math.cos(t) - Math.abs(Math.sin(t)) * Math.sin(t))
})
const SIZE = 200
const c = document.body.appendChild(
Object.assign(document.createElement`canvas`,
{ width: SIZE, height: SIZE }
)).getContext`2d`
c.fillStyle = 'black'
c.fillRect(0, 0, SIZE, SIZE)
let t = 0
setInterval(() => {
const { x, y } = rect(20, 20, 60, 70, t)
c.fillStyle = 'rgba(255, 0, 0, .1)'
c.fillRect(x, y, 10, 10)
t += .05
}, 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…