自动调整SVG内的鼠标位置

Riw*_*all 49 javascript svg

我遇到了关于鼠标光标在我的SVG文档中的位置的麻烦.我想在HTML页面中使用JavaScript设计一个在拖动时跟随光标的电位计.

我尝试了evt.clientX/Y和evt.screenX/Y,但由于我的SVG处于自动缩放状态,因此我的SVG中的坐标是不同的.我现在一直在寻找答案,但我找不到任何解决方案(要么实时了解我的SVG重新缩放因子,要么在SVG坐标系统中具有鼠标位置功能).

轮换将遵循一个简单的规则:

if(evt.screenX <xc)

ang = Math.atan((evt.screenY - yc)/(evt.screenX - xc))*360 /(2*Math.PI) - 90;
if(evt.screenX> xc)
ang = Math.atan((evt.screenY - yc)/(evt.screenX - xc))*360 /(2*Math.PI)+ 90;

用(xc; yc)作为旋转中心,用SVG中鼠标的坐标替换所有evt.screenX/Y.

Phr*_*ogz 112

请参阅此代码,其中不仅展示了如何从屏幕空间转换为全局SVG空间,还展示了如何将SVG空间中的点转换为元素的转换空间:http:
//phrogz.net/svg/drag_under_transformation.xhtml

简而言之:

// Find your root SVG element
var svg = document.querySelector('svg');

// Create an SVGPoint for future math
var pt = svg.createSVGPoint();

// Get point in global SVG space
function cursorPoint(evt){
  pt.x = evt.clientX; pt.y = evt.clientY;
  return pt.matrixTransform(svg.getScreenCTM().inverse());
}

svg.addEventListener('mousemove',function(evt){
  var loc = cursorPoint(evt);
  // Use loc.x and loc.y here
},false);
Run Code Online (Sandbox Code Playgroud)

编辑:我已根据您的需求创建了一个示例(尽管仅在全球SVG空间中):http:
//phrogz.net/svg/rotate-to-point-at-cursor.svg

它为上面添加了以下方法:

function rotateElement(el,originX,originY,towardsX,towardsY){
  var angle = Math.atan2(towardsY-originY,towardsX-originX);
  var degrees = angle*180/Math.PI + 90;
  el.setAttribute(
    'transform',
    'translate('+originX+','+originY+') ' +
      'rotate('+degrees+') ' +
      'translate('+(-originX)+','+(-originY)+')'
  );
}
Run Code Online (Sandbox Code Playgroud)

  • 我知道这不应该写成评论,而是:"非常感谢你!".几个星期以来,我一直在努力解决类似问题,直到找到答案为止.现在我的代码完美无缺! (6认同)