Rotated bounding rectangle
Computing the size of a rectangle that bounds another given a particular rotation
by soulwire
CSS
html, body {
background: #fff;
margin: 0;
}
Babel + JSX
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const width = canvas.width = window.innerWidth
const height = canvas.height = window.innerHeight
document.body.appendChild(canvas)
const button = document.createElement('button')
button.addEventListener('click', () => refresh())
button.innerText = 'Refresh'
button.style.position = 'absolute'
button.style.left = '20px'
button.style.top = '20px'
document.body.appendChild(button)
const refresh = (w, h, t) => {
const scale = window.devicePixelRatio || 1
canvas.width = width * scale
canvas.height = height * scale
canvas.style.width = width + 'px'
canvas.style.height = height + 'px'
ctx.scale(scale, scale)
// Create a random rectangle
const theta = t || Math.random() * Math.PI / 2
const w1 = w || width * (0.1 + Math.random() * 0.4)
const h1 = h || height * (0.1 + Math.random() * 0.4)
// Compute bounding rectangle
// http://math.stackexchange.com/questions/592701/calculating-dimensions-of-rotated-rectangle-for-it-to-to-mask-original
// w′=v+s=hsinα+wcosα
// h′=t+u=wsinα+hcosα
const sin = Math.abs(Math.sin(theta))
const cos = Math.abs(Math.cos(theta))
const w2 = h1 * sin + w1 * cos
const h2 = w1 * sin + h1 * cos
console.log(~~w1, ~~h1, ~~w2, ~~h2)
// Render
ctx.translate(width / 2, height / 2)
// Original rect
ctx.fillStyle = '#03A9F4'
ctx.fillRect(-w1/2, -h1/2, w1, h1)
// Bounding rect
ctx.rotate(theta)
ctx.fillStyle = '#8BC34A'
ctx.globalAlpha = 0.5
ctx.fillRect(-w2/2, -h2/2, w2, h2)
}
refresh()
let t = 0
//setInterval(() => {refresh(100, 80, t += 0.005)}, 60/1000)