JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<div id="buttonContainer">
<button id="growRightSide">Grow X</button>
<button id="growBottomSide" >Grow Y</button>
<button id="rotateCW">Rotate Clockwise</button>
<button id="rotateACW">Rotate Anti-clockwise</button>
</div>
<div id="container">
</div>
</body>
CSS
body {
background-color:white;
background-image: linear-gradient(rgba(0,0,0,.3) 2px, transparent 2px),
linear-gradient(90deg, rgba(0,0,0,.3) 2px, transparent 2px),
linear-gradient(rgba(0,0,0,.3) 1px, transparent 1px),
linear-gradient(90deg, rgba(0,0,0,.3) 1px, transparent 1px);
background-size:100px 100px, 100px 100px, 20px 20px, 20px 20px;
background-position:-2px -2px, -2px -2px, -1px -1px, -1px -1px
}
canvas {
position: absolute;
top: 35px;
left: 0px;
box-sizing: border-box;
border: 1px solid red;
}
#buttonContainer {
position: fixed;
z-index: 10;
}
JavaScript
var SHADOW_OFFSET = 30;
var counter = 0;
var arr = [{
top: 300,
left: 320,
width: 120,
height: 60,
rotation: -Math.PI / 180 * 15
},
{
top: 150,
left: 50,
width: 200,
height: 80,
rotation: Math.PI / 180 * 46
}];
function getDisplayDimensions(shape) {
var w2 = shape.width / 2;
var h2 = shape.height / 2;
var alpha = Math.atan2(h2, w2);
var length = Math.sqrt(Math.pow(h2, 2) + Math.pow(w2, 2));
var width1 = Math.abs(Math.cos(shape.rotation + alpha) * length) * 2;
var height1 = Math.abs(Math.sin(shape.rotation + alpha) * length) * 2;
var width2 = Math.abs(Math.cos(shape.rotation - alpha) * length) * 2;
var height2 = Math.abs(Math.sin(shape.rotation - alpha) * length) * 2;
console.log(width1, width2, height1, height2);
var newWidth = Math.round((width1 > width2 ? width1 : width2) + (2 * SHADOW_OFFSET));
var newHeight = Math.round((height1 > height2 ? height1 : height2) + (2 * SHADOW_OFFSET));
return {
width: newWidth,
height: newHeight
};
}
function resizeCanvas(shape, canvas) {
console.log('resizeCanvas')
var displayDims = getDisplayDimensions(shape);
canvas.width = displayDims.width;
canvas.height = displayDims.height;
console.log('canvas',canvas)
var corrX = (displayDims.width - (shape.width + 2 * SHADOW_OFFSET)) / 2;
var corrY = (displayDims.height - (shape.height + 2 * SHADOW_OFFSET)) / 2;
canvas.style.top = shape.top - 1 - corrY - SHADOW_OFFSET + 'px';
canvas.style.left = shape.left - 1 - corrX - SHADOW_OFFSET + 'px';
return { x: corrX, y: corrY };
}
function initCanvas(shape) {
var canvas = document.createElement('canvas');
document.getElementById('container').appendChild(canvas)
resizeCanvas(shape, canvas);
shape.canvas = canvas;
//return canvas;
}
function draw(shape) {
console.log('draw')
var h2 = shape.height;
var w2 = shape.width;
var x = w2;
var y = h2;
var canvas = shape.canvas;
resizeCanvas(shape,...