Auto-crop rotated rectangle

by PhilQ

HTML

<canvas></canvas>

JavaScript

var TO_RADIAN = Math.PI / 180;
let width = 100;
let height = 200;

let angle = 135;

$(document).ready(function() {

	let refAngle1 = angle > 90 && angle < 270 ? 180 : 0;
	let refAngle2 = 0;
	let radius = width / 2;
	let c = {
		x: 0,
		y: 0
	};
	let p1 = {
		x: c.x + Math.cos(refAngle1 * TO_RADIAN) * radius,
		y: c.y + Math.sin(refAngle1 * TO_RADIAN) * radius
	};
	let p2 = {
		x: c.x + Math.cos((refAngle2 + angle) * TO_RADIAN) * radius,
		y: c.y + Math.sin((refAngle2 + angle) * TO_RADIAN) * radius
	};

	let cnv = $('canvas')[0];
	let ctx = cnv.getContext('2d');
	
	cnv.width = width;
	cnv.height = height;

	ctx.translate(width / 2, height / 2);
	ctx.save();

	ctx.strokeStyle = '#cccccc';
	ctx.beginPath();
	ctx.arc(0, 0, width / 2, 0, 2*Math.PI);
	ctx.closePath();
	ctx.stroke();

	ctx.fillStyle = '#0000ff';
	ctx.fillRect(width / -2, height / -2, width, height);
	
	ctx.rotate(angle * TO_RADIAN);
	
	ctx.fillStyle = '#ff0000';
	ctx.fillRect(width / -2, height / -2, width, height);

	ctx.restore();

	ctx.strokeStyle = '#cccccc';
	ctx.beginPath();
	ctx.arc(0, 0, width / 2, 0, 2*Math.PI);
	ctx.closePath();
	ctx.stroke();

	ctx.fillStyle = '#ffff00';
	ctx.beginPath();
	ctx.arc(p1.x, p1.y, 3, 0, 2*Math.PI);
	ctx.closePath();
	ctx.fill();

	ctx.fillStyle = '#00ffff';
	ctx.beginPath();
	ctx.arc(p2.x, p2.y, 3, 0, 2*Math.PI);
	ctx.closePath();
	ctx.fill();

	let intersect = getIntersect(c, p1, p2);
	if (angle % 180 > 0 && intersect !== false) {
		let diff = Math.abs(intersect.y - p1.y);

		ctx.fillStyle = '#00ff00';
		ctx.beginPath();
		ctx.arc(intersect.x, intersect.y, 3, 0, 2*Math.PI);
		ctx.closePath();
		ctx.fill();

		ctx.strokeStyle = '#ff00ff';
		ctx.strokeRect(width / -2, -diff, width, 2 * diff);
	}
	
});


function getIntersect(c, p1, p2) {
	var n1x = p1.x - c.x;
	var n1y = p1.y - c.y;
	var n2x = p2.x - c.x;
	var n2y = p2.y - c.y;
	var d1 = n1x * p1.x + n1y * p1.y;
	var d2 = n2x * p2.x + n2y * p2.y;

	var det = n1y * n2x - n1x * n2y;
	if (det === 0) {
		// The lines...