I need to figure the ending bounding rect of an element before the css transform: matrix() transformation is applied. I have no idea really where to start and can't find any good articles addressing this.
So given you have the original position of the element with getBoundingClientRect() is there a reliable way to find the ending position if you have the matrix that is supposed to be applied.
I have built a scroll controller and I am trying to map the elements progress through the screen but I need the starting and ending position of the element. So I would need the position of the element after the css transformation is applied to figure out when the element has left the screen. Right now i am just applying the matrix and then running getBoundingClientRect() again. But this seems a bit hacky.
So given you have the original and ending matrix. And then you run the getBoundingClientRect() on the element to find its position. Is there a mathematical way to calculate the new bounding rect?
So for this example we will just use a 6 value matrix. But it would be nice to apply it to a full 16 value matrix as well:
const boundingRect = element.getBoundingClientRect();
const startingMatrix = [1, 0, 0, 1, 0, 0];
const endingMatrix = [2, 1, -1, 2, 200, 400];
// Now calculate the new bounding rect of element after ending matrix is applied.
I have tried the following based on this article https://dev.opera.com/articles/understanding-the-css-transforms-matrix/ recommended by the comments below. There is something that I obviously am missing or dont understand. Here is my attempt:
const applyToPoint = (matrix, point) => {
const multiplied = [
matrix[0] * point[0],
matrix[1] * point[1],
matrix[2] * point[0],
matrix[3] * point[1],
matrix[4] * point[0],
matrix[5] * point[1]
]
const result = [
multiplied[0] + multiplied[2] + multiplied[4],
multiplied[1] + multiplied[3] + multiplied[5]
]
return result
}
const box = document.querySelector('.box')
const startingMatrix = [1, 0, 0, 1, 0, 0]
box.style.transform = `matrix(1,0,0,1,0,0)`
const startingRect = box.getBoundingClientRect()
const endingMatrix = [2, 1, -1, 2, 200, 400]
box.style.transform = `matrix(2,1,-1,2,200,400)`
const endingRect = box.getBoundingClientRect()
const newPoint = applyToPoint(endingMatrix, [startingRect.x, startingRect.y])
console.log(newPoint, endingRect)
.box {
height: 50px;
width: 50px;
background: green;
margin: 50px 0;
}
<div class="box"></div>
I also tried :
const applyToPoint = (matrix, point) => [
matrix[0] * point[0] + matrix[2] * point[1] + matrix[4],
matrix[1] * point[0] + matrix[3] * point[1] + matrix[5]
]
Any help would be appreciated. Or pointers in the right direction.