JSFiddle - React, Tailwind, and code Playground
by Augustus Yuan
HTML
<div id="controls">
Diagonal:
<button id="q1">up-right</button>
<button id="q2">down-right</button>
<button id="q3">down-left</button>
<button id="q4">up-left</button>
<br>
Horizontal:
<button id="h1">left-to-right</button>
<button id="h2">right-to-left</button>
<br>
Vertical:
<button id="v1">top-to-bottom</button>
<button id="v2">bottom-to-top</button>
</div>
<div style="margin:20px; position:relative; border:1px dashed #e0e0e0; width:120px; height:120px;">
<div id="x"></div>
</div>
<div id="params">
startAngle:<span id="startAngle"></span>
endAngle:<span id="endAngle"></span>
length:<span id="length"></span>
</div>
CSS
div#x {
position: relative;
left: 50px;
top: 50px;
width: 20px;
height: 20px;
background-color: #000;
}
JavaScript
$(function() {
function r2d(x) {
/* radians to degrees */
return x * 180 / Math.PI;
}
function smaller(x, y) {
/* minimum abs value, preserving sign */
var x_ = Math.abs(x);
var y_ = Math.abs(y);
return (Math.min(x_, y_) === x_) ? x : y;
}
function anim($el, end) {
var current = $el.position();
var slope1 = (end.top - current.top) / (end.left - current.left);
var slope2 = 1 / slope1;
var endAngle = r2d(Math.atan(smaller(slope1, slope2)));
var startAngle = -endAngle;
var length = 1/3;
$("#endAngle").text(endAngle);
$("#startAngle").text(startAngle);
$("#length").text(length);
var path = {
start: {
x: current.left,
y: current.top,
angle: startAngle,
length: length
},
end: {
x: end.left,
y: end.top,
angle: endAngle,
length: length
}
};
$el.animate({ path: new jQuery.path.bezier(path) });
}
$("#q1").on('click', function() {
var current = { left:0, top:100 };
var end = { left:100, top:0 };
anim( $("#x").css(current), end );
});
$("#q2").on('click', function() {
var current = { left:0, top:0 };
var end = { left:100, top:100 };
anim( $("#x").css(current), end );
});
$("#q3").on('click', function() {
var current = { left:100, top:0 };
var end = { left:0, top:100 };
anim( $("#x").css(current), end );
});
$("#q4").on('click', function() {
var current = { left:100, top:100 };
var end = { left:0, top:0 };
anim( $("#x").css(current), end );
});
$("#h1").on('click', function() {
//Horizontal - left-to-right
var current = { left:0, top:50 };
var end = { left:100, top:50 };
anim( $("#x").css(current), end );
});
$("#h2").on('click', function() {
//Horizontal - right-to-left
var current = { left:100, top:50 };
var end = { left:0, top:50 };
anim( $("#x").css(current), end );
});
$("#v1").on('click', function() {
//Vertical - top-to-bottom
var current = { left:50, top:0 };
var end = { left:50, top:100 };
anim(...