Offset after translateZ
Finding the offset of an element after translateZ has been applied.
HTML
<p>The slider changes the translateZ of the element "Two"</p>
<p>The red circle is re-positioned using javascript</p>
<div id="stage">
<div>
<div id="one">One</div>
<div id="two">Two</div>
</div>
<div id="three"></div>
</div>
<input type="range" id="perspective-control" value="0" min="0" max="10">
CSS
p {
margin: 10px;
text-align: center;
}
#stage {
position: relative;
width: 400px;
height: 300px;
background: rgba(255,0,0,0.2);
-webkit-perspective: 100;
margin: 10px auto;
}
#stage div div {
position: absolute;
width: 50px;
height: 50px;
background: blue;
text-align: center;
line-height: 50px;
color: #fff;
-webkit-transform: translateZ(0);
/*-webkit-transition: all 0.2s ease-in-out;*/
}
#one {
top: 10%;
left: 10%;
}
#two {
top: 100%;
left: 100%;
}
#three {
position: absolute;
background: none;
width: 10px;
height: 10px;
margin: -5px 0 0 -5px;
box-shadow: 0 0 0 2px red;
border-radius: 5px;
}
#perspective-control {
display: block;
width: 200px;
margin: auto;
}
JavaScript
var stage = $('#stage');
var boxes = stage.children('div').children();
var pos = [parseInt($('#two').css('left')),
parseInt($('#two').css('top'))]
var z = 0;
var ChangePerspective = function(i) {
$(boxes.get(1)).css('-webkit-transform', 'translateZ(' + (i * -100) + 'px)');
z = (i * -100);
}
var xy = function() {
var two = $(boxes.get(1));
var x = pos[0] - (stage.width() / 2);
var y = pos[1] - (stage.height() / 2);
var bz = parseInt(stage.css('perspective'))
x = bx(x, bz, z) + (stage.width() / 2)
y = bx(y, bz, z) + (stage.height() / 2);
console.log(x,y)
$('#three').css({
'left': x + 'px',
'top': y + 'px'
})
}
var bx = function(ax, bz, z) {
var az = bz + z * -1;
return ax * bz / az;
}
$('#perspective-control').change(function() {
ChangePerspective(parseInt($(this).val()));
xy();
});
xy();