I’m trying to translate a rotated element but when I do so, the element translates considering the rotated axis. I’m trying to translate the element considering the axis pre rotation. How do I do that?
I’ve created a jsfiddle to illustrate the issue : https://jsfiddle.net/c03wpyuz/6/
$(document).ready(() => {
var tx = 0;
var ty = 0;
var ag = 0;
var el = $('#test');
setTimeout(() => {
ag = 45;
el.css('transform', 'rotate(' + ag + 'deg)');
}, 1000);
setTimeout(() => {
tx = 100;
ty = 0;
el.css('transform', 'rotate(' + ag + 'deg) translate3d(' + tx + 'px, ' + ty + 'px, 0)');
}, 2000);
});
#test {
width: 200px;
height: 100px;
background-color: red;
transform-origin: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="test">
</div>
The element will rotate after 1 second then after 2 seconds it will translate. The issue is that I’m only translating it over the X axis but the axis is then rotated.
1
Try putting translate3d
before rotate
:
$(document).ready(() => {
var tx = 0;
var ty = 0;
var ag = 0;
var el = $('#test');
setTimeout(() => {
ag = 45;
el.css('transform', 'rotate('+ag+'deg)');
}, 1000);
setTimeout(() => {
tx = 100;
ty = 0;
el.css('transform', 'translate3d('+tx+'px, '+ty+'px, 0) rotate('+ag+'deg)');
}, 2000);
});
#test{
width: 200px;
height: 100px;
background-color: red;
transform-origin: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="test">
</div>
Another approach is to use translate
and rotate
separately, instead of transform
(but be aware of their coverage):
$(document).ready(() => {
var tx = 0;
var ty = 0;
var ag = 0;
var el = $('#test');
setTimeout(() => {
ag = 45;
el.css('rotate', `${ag}deg`);
}, 1000);
setTimeout(() => {
tx = 100;
ty = 0;
el.css('translate', `${tx}px ${ty}px 0px`);
}, 2000);
});
#test{
width: 200px;
height: 100px;
background-color: red;
transform-origin: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="test">
</div>
1