Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple .style.transform on same element

It seems that by using two cases of obj.style.transform in succession results in only the first statement being executed. Please see the below code. A full example is on CodePen.

function animateObject(x, y, z){
    object = document.getElementsByClassName('cub-1')[0];

    object.style.transform = "rotateX(" + x + "deg)";
    object.style.transform = "rotateY(" + y + "deg)";
    alert("")
}

In the full example, I am reading lines from a text area which contains x, y and z positions of an object, converting the values from radians to degrees and then animating my 3d object using these values.

like image 923
Mike Resoli Avatar asked Mar 13 '23 19:03

Mike Resoli


1 Answers

When applying multiple transforms to the same element, they should be added as space separated values to the same property like below. Otherwise, they would get overwritten (only the rotateY will be applied because it is the latest).

object.style.transform = "rotateX(" + x + "deg)";
object.style.transform += "rotateY(" + y + "deg)";

I have added an alert of the object.style.transform to both the original snippet and the modified version and we can see how the original one always outputs only the rotateY whereas the changed one outputs both rotateX() and rotateY() together.

Original Code with Alerts added | Modified Code with Alerts added

like image 111
Harry Avatar answered Mar 23 '23 10:03

Harry