猿问

是否有任何处理程序可以旋转对象?

这似乎在 interact.js 的移动版本中是可能的,而我正在寻找一种也可以在标准桌面浏览器中使用的解决方案。


四季花海
浏览 93回答 1
1回答

牧羊人nacy

这是代码:/*  * 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">&circlearrowright;</div></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答