1 回答

TA貢獻1862條經驗 獲得超7個贊
這是代碼:
/*?
?* Some code borrowed from: https://codepen.io/taye/pen/wrrxKb
*/
interact('.rotation-handle')
? .draggable({
? ? onstart: function(event) {
? ? ? var box = event.target.parentElement;
? ? ? var rect = box.getBoundingClientRect();
? ? ? // store the center as the element has css `transform-origin: center center`
? ? ? box.setAttribute('data-center-x', rect.left + rect.width / 2);
? ? ? box.setAttribute('data-center-y', rect.top + rect.height / 2);
? ? ? // get the angle of the element when the drag starts
? ? ? box.setAttribute('data-angle', getDragAngle(event));
? ? },
? ? onmove: function(event) {
? ? ? var box = event.target.parentElement;
? ? ? var pos = {
? ? ? ? x: parseFloat(box.getAttribute('data-x')) || 0,
? ? ? ? y: parseFloat(box.getAttribute('data-y')) || 0
? ? ? };
? ? ? var angle = getDragAngle(event);
? ? ? // update transform style on dragmove
? ? ? box.style.transform = 'translate(' + pos.x + 'px, ' + pos.y + 'px) rotate(' + angle + 'rad' + ')';
? ? },
? ? onend: function(event) {
? ? ? var box = event.target.parentElement;
? ? ? // save the angle on dragend
? ? ? box.setAttribute('data-angle', getDragAngle(event));
? ? },
? })
function getDragAngle(event) {
? var box = event.target.parentElement;
? var startAngle = parseFloat(box.getAttribute('data-angle')) || 0;
? var center = {
? ? x: parseFloat(box.getAttribute('data-center-x')) || 0,
? ? y: parseFloat(box.getAttribute('data-center-y')) || 0
? };
? var angle = Math.atan2(center.y - event.clientY,
? ? center.x - event.clientX);
? return angle - startAngle;
}
body {
? font-family: sans-serif;
}
.box {
? width: 150px;
? height: 100px;
? position: relative;
? background-color: #4be091;
? border-radius: 6px;
}
.rotation-handle {
? padding: 3px 4px;
? display: table;
? position: absolute;
? left: 50%;
? right: 50%;
? bottom: -35px;
? background-color: #ff1661;
? border-radius: 10rem;
? line-height: 1;
? text-align: center;
? font-weight: bold;
? color: #fff;
? cursor: move;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/interact.js/1.2.9/interact.min.js"></script>
<p>
? <strong>Rotate the box using the red handle.</strong>
</p>
<div class="box">
? <div class="rotation-handle">↻</div>
</div>
添加回答
舉報