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

查看:476
本文介绍了自动缩放的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/Y和evt.screenX/Y,但是由于我的SVG处于自动缩放中,因此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)
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;

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)为旋转中心,并将所有evt.screenX/Y替换为我的SVG内部的鼠标坐标.

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天全站免登陆