How to resize an element to the cursor with respect to the element's rotation?

Viewed 203

I'm trying to make some code to resize an element to the mouse cursor, with the element "anchored" to a certain starting position. However, it quickly falls apart when the element is rotated. Here's my code right now:

var block = document.getElementById("block");
var desiredX = block.offsetLeft;
var desiredY = block.offsetTop;
function resize(event) {
    block.style.left = Math.min(event.pageX, desiredX) + "px";
    block.style.top = Math.min(event.pageY, desiredY) + "px";
    block.style.width = Math.abs(event.pageX - desiredX) + "px";
    block.style.height = Math.abs(event.pageY - desiredY) + "px";
}
document.addEventListener("mousemove", resize);
#block {
    height: 10em;
    width: 2em;
    background-color: gray;
    border: 1px solid black;
    position: absolute;
  zIndex: 1;
    cursor: pointer;
}
#inputs {
  zIndex: 2;
  position: absolute;
  right: 10px;
  bottom: 10px;
}
<div id="block" style="left: 50px; top: 50px;"></div>
<div id="inputs"><label for="rotation">Rotate block:</label><br /><input type="range" min="0" max="360" value="0" id="rotation" style="width: 250px" oninput="block.style.transform = 'rotate(' + this.value + 'deg)'"></input></div>

How can I make it so that the corner of the block will always reach the cursor, regardless of rotation?

I did find a similar question/answer (Resizing Handles on a Rotated Element), but I couldn't figure out how to properly adapt the answer for this situation. Here was my failed attempt at doing so:

var block = document.getElementById("block");
var desiredX = block.offsetLeft;
var desiredY = block.offsetTop;
function resize(event) {
  var angle = +block.style.transform.replace(/[^0-9]/gi, '')*(Math.PI/180);
  var len = Math.sqrt(Math.pow(event.pageX - block.offsetLeft, 2)+Math.pow(event.pageY - block.offsetTop, 2));
    block.style.left = Math.min(event.pageX, desiredX) + "px";
    block.style.top = Math.min(event.pageY, desiredY) + "px";
    block.style.width = Math.abs(Math.sin(angle)*len) + "px";
    block.style.height = Math.abs(Math.cos(angle)*len) + "px";
}
document.addEventListener("mousemove", resize);
#block {
        height: 10em;
        width: 2em;
        background-color: gray;
        border: 1px solid black;
        position: absolute;
      zIndex: 1;
        cursor: pointer;
    }
    #inputs {
      zIndex: 2;
      position: absolute;
      right: 10px;
      bottom: 10px;
    }
<div id="block" style="left: 50px; top: 50px;"></div>
<div id="inputs"><label for="rotation">Rotate block:</label><br /><input type="range" min="0" max="360" value="0" id="rotation" style="width: 250px" oninput="block.style.transform = 'rotate(' + this.value + 'deg)'"></input></div>

0 Answers
Related