Задача: сделать вращаемый мышью регулятор громкости с диапазоном значений от 0 до 100.
Решение:
<div class="rotate-container">
<div id="rotate-shadow">
<div id="rotate"></div>
</div>
</div>
<input type="text" id="rotate-value" value="0">
<script src="/jquery.min.js"></script>
<script>
(function(){
var init, rotate, start, stop, active = false,
angle = 0,
rotation = 0,
startAngle = 0,
center = {x: 0,y: 0},
R2D = 180 / Math.PI,
rot = document.getElementById('rotate');
init = function() {
rot.addEventListener("mousedown", start, false);
$(document).bind('mousemove', function(event) {
if (active === true) {
event.preventDefault();
rotate(event);
}
});
$(document).bind('mouseup', function(event) {
event.preventDefault();
stop(event);
});
};
start = function(e) {
e.preventDefault();
var bb = this.getBoundingClientRect(),
t = bb.top,
l = bb.left,
h = bb.height,
w = bb.width,
x, y;
center = {x: l + (w / 2), y: t + (h / 2)};
x = e.clientX - center.x;
y = e.clientY - center.y;
startAngle = R2D * Math.atan2(y, x);
return active = true;
};
rotate = function(e) {
e.preventDefault();
var x = e.clientX - center.x,
y = e.clientY - center.y,
d = R2D * Math.atan2(y, x);
rotation = d - startAngle;
let val = angle + rotation % 360;
if (val < 0) {
val = 360 + val;
}
val = (val / 360) * 100;
$('#rotate-value').val(Math.round(val));
return rot.style.transform = "rotate(" + (angle + rotation) + "deg)";
};
stop = function() {
angle += rotation;
return active = false;
};
init();
}).call(this);
</script>
CSS-стили:
.rotate-container {
width: 200px;
height: 200px;
position: relative;
margin-bottom: 40px;
}
#rotate-shadow {
position: relative;
width: 100%;
height: 100%;
border-radius: 50%;
box-shadow: 0px 6px 16px #888;
}
#rotate {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
border-radius: 50%;
box-sizing: border-box;
border: 2px solid #000;
background: linear-gradient(0deg, #333, #444, #333);
}
#rotate::before {
content: "";
position: absolute;
left: 0;
right: 0;
margin: 3% auto;
height: 12%;
width: 1.4%;
border-radius: 25%;
background: orange;
box-shadow: 0 0 2px 0 orange;
}
#rotate-value {
text-align: center;
width: 101px;
height: 30px;
line-height: 30px;
font-size: 18px;
padding: 0;
margin: 0 auto;
display: block;
}