JSFiddle - React, Tailwind, and code Playground
by m1erickson
HTML
<canvas id="canvas" width=300 height=300></canvas>
CSS
body {
background-color: ivory;
}
canvas {
border:1px solid red;
}
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// blue rect's info
var blueX = 421;
var blueY = 343;
var blueWidth = 81;
var blueHeight = 44;
var blueAngle = -25.00 * Math.PI / 180;
// load the image
var img = new Image();
img.onload = start;
img.src = "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/temp6.jpg";
function start() {
// create 2 temporary canvases
var canvas1 = document.createElement("canvas");
var ctx1 = canvas1.getContext("2d");
var canvas2 = document.createElement("canvas");
var ctx2 = canvas2.getContext("2d");
// get the boundingbox of the rotated blue box
var rectBB = getRotatedRectBB(blueX, blueY, blueWidth, blueHeight, blueAngle);
// clip the boundingbox of the rotated blue rect
// to a temporary canvas
canvas1.width = canvas2.width = rectBB.width;
canvas1.height = canvas2.height = rectBB.height;
ctx1.drawImage(img,
rectBB.cx - rectBB.width / 2,
rectBB.cy - rectBB.height / 2,
rectBB.width,
rectBB.height,
0, 0, rectBB.width, rectBB.height);
// unrotate the blue rect on the temporary canvas
ctx2.translate(canvas1.width / 2, canvas1.height / 2);
ctx2.rotate(-blueAngle);
ctx2.drawImage(canvas1, -canvas1.width / 2, -canvas1.height / 2);
// draw the blue rect to the display canvas
var offX = rectBB.width / 2 - blueWidth / 2;
var offY = rectBB.height / 2 - blueHeight / 2;
canvas.width = blueWidth;
canvas.height = blueHeight;
ctx.drawImage(canvas2, -offX, -offY);
} // end start
// Utility: get bounding box of rotated rectangle
function getRotatedRectBB(x, y, width, height, rAngle) {
var absCos = Math.abs(Math.cos(rAngle));
var absSin = Math.abs(Math.sin(rAngle));
var cx = x + width / 2 * Math.cos(rAngle) - height / 2 * Math.sin(rAngle);
var cy = y + width / 2 * Math.sin(rAngle) + height / 2 * Math.cos(rAngle);
var w = width * absCos + height * absSin;
...