js平面旋转

在项目开发中,选装效果经常会用到,下面简单的封装了一个旋转插件:

(function(){
  var rotated = 0;
  var rotatable = (function(){
    var init = function(selector) {
      var box = document.querySelector(selector);
      addHandler(box);
    }
    var addHandler = function(box) {
      var line = createElement('div'),
          innerDot = createElement('div'),
          outerDot = createElement('div');
      box.style.cssText = 'position: relative';
      line.style.cssText = 'position: absolute; left: 50%;top: 50%; width: 70%;border-top: 2px dashed #f00;';
      appendEement(line, box);
      innerDot.style.cssText = 'width: 10px; height: 10px; border-radius: 50%; position: absolute; left: 0; top: -6px; background: #f00;';
      outerDot.style.cssText = 'width: 10px; height: 10px; border-radius: 50%; position: absolute; right: 0; top: -6px; background: #f00;';
      outerDot.className = 'outerDot';
      appendEement(innerDot, line);
      appendEement(outerDot, line);
      bindRotateEvents(outerDot, box);
    }
    var createElement = function(type) {
      return document.createElement(type);
    }
    var appendEement = function(node, parent) {
      var parent = parent || document.body;
      parent.appendChild(node);
    }
    var bindRotateEvents = function(node, box) {
      var point = getConterPoint(box);
      node.onmousedown = function() {
        var event = window.event,
            prevAngle = Math.atan2(event.pageY - point.y, event.pageX - point.x) - rotated;
        document.onmousemove = function() {
          var event = window.event,
              angle = Math.atan2(event.pageY - point.y, event.pageX - point.x);
          rotated = angle;
          doRotate(box, Math.floor((angle - prevAngle) * 180 / Math.PI));
        }
        document.onmouseup = function() {
          document.onmousemove = null;
          document.onmouseup = null;
        }
      }
      node.ondragstart = function(event) {
        event.preventDefault();
        return false;
      }
    }
    var getConterPoint = function(box) {
      return {
        x: box.offsetLeft + box.offsetWidth / 2,
        y: box.offsetTop + box.offsetHeight / 2
      };
    }
    var doRotate = function(box, angle) {
      box.style.cssText = 'position: relative; transform: rotate(' + angle + 'deg);';
    }
    return { init : init }
  })();
  window.rotatable = rotatable;
})();

猛戳这里查看实例

  • 支付宝二维码 支付宝
  • 微信二维码 微信
相关文章