鼠标在自动缩放的 SVG 中的位置 [英] Mouse position inside autoscaled SVG

查看:36
本文介绍了鼠标在自动缩放的 SVG 中的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了鼠标光标在 SVG 文档中的位置问题.我想设计一个电位器,拖动时会跟随光标,在 HTML 页面中使用 JavaScript.

I am experiencing troubles concerning the position of mouse cursor inside my SVG document. I'd like to design a potentiometer that will follow the cursor when dragged, using JavaScript in an HTML page.

我尝试了 evt.clientX/Yevt.screenX/Y 但由于我的 SVG 处于 autoscale,我的 SVG 内的坐标是不同的.我几天来一直在寻找答案,但我找不到任何解决方案(要么实时了解我的 SVG 缩放因子,要么在 SVG 坐标系中具有鼠标定位功能).

I tried evt.clientX/Y and evt.screenX/Y but as my SVG is in autoscale, coordinates inside my SVG are different. I have been searching for an answer for days now but I couldn't find any solution (either knowing my SVG rescaling factor in real time or have a function for mouse location in SVG coordinates system).

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

The rotation will follow a simple rule:

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.

With (xc;yc) as center of rotation and replacing all evt.screenX/Y by the coordinates of the mouse inside my SVG.

推荐答案

看这段代码,不仅展示了如何从屏幕空间转换到全局SVG空间,还展示了如何将一个点从SVG空间转换到转换后的空间元素的:
http://phrogz.net/svg/drag_under_transformation.xhtml

See this code, which not only shows how to transform from screen space to global SVG space, but also how to transform a point from SVG space into the transformed space of an element:
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);

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

Edit: I've created a sample tailored to your needs (albeit only in global SVG space):
http://phrogz.net/svg/rotate-to-point-at-cursor.svg

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

It adds the following method to the above:

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)+')'
  );
}

这篇关于鼠标在自动缩放的 SVG 中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆