Raphaeljs and css 3d transforms

by trolleymusic

HTML

<script src="https://raw.github.com/DmitryBaranovskiy/raphael/52bff469f60988f1391e8b3d7cb5349163df8ba1/raphael-min.js"></script>
<div id="stage">
    <div id="one">One</div>
    <div id="two">Two</div>
</div>

<input type="range" id="perspective-control" value="0" min="0" max="10">

CSS

#stage {
    position: relative;
    width: 300px;
    height: 300px;
    background: rgba(255,0,0,0.2);
    -webkit-perspective: 1000;
    margin: 10px auto;
}
#stage 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 {
    bottom: 20%;
    right: 10%;
}

#perspective-control {
    display: block;
    width: 200px;
    margin: auto;
}

JavaScript

var stage = $('#stage');
var boxes = stage.children('div');
var line = null;

var paper = Raphael(stage.get(0), stage.width(), stage.height());

var ChangePerspective = function(i) {
    $(boxes.get(1)).css('-webkit-transform', 'translateZ(' + (i * -100) + 'px)');
}

var DrawLine = function() {
    var one = $(boxes.get(0));
    var two = $(boxes.get(1));
    var pos = [[one.position().left + one.width(), one.position().top + one.height()],
        [two.position().left, two.position().top]];
    var coords = "M" + pos[0].join(' ') + "L" + pos[1].join(' ');
    if (line) {
        line.attr({path:coords});
    } else {
        line = paper.path(coords);
    }
    console.log(pos[0].join(','), pos[1].join(','));
}
    
$('#perspective-control').change(function() {
    ChangePerspective(parseInt($(this).val()));
    DrawLine();
});

DrawLine();