SVG捕获鼠标坐标 [英] SVG Capturing Mouse Coordinates

查看:559
本文介绍了SVG捕获鼠标坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前已经知道有关svg鼠标坐标的问题,但我对目前正在经历的行为感到非常困惑,并且似乎没有一个线程可以解决它。

I know questions regarding svg mouse coordinates have been asked here before, but I'm quite puzzled by the current behavior I'm experiencing and none of the threads quite seems to address it.

我用来捕捉坐标的方法:

The method I use for capturing coordinates:

var pt = svg.createSVGPoint();  // Created once for document

function alert_coords(evt) {
    pt.x = evt.clientX;
    pt.y = evt.clientY;

    // The cursor point, translated into svg coordinates
    var cursorpt =  pt.matrixTransform(svg.getScreenCTM().inverse());
    console.log("(" + cursorpt.x + ", " + cursorpt.y + ")");
}

问题在于将鼠标点击坐标转换为用户空间中的svg坐标。我正在使用坐标在屏幕上拖动一个矩形,当光标在svg空间中向右移动时,坐标变得越来越倾斜。为了以简单的方式测试这个,我在全局svg空间中放置了三个矩形(100,500),(500,500),(1000,500)和(1000,200)。使用简单的记录功能,我接收的坐标(鼠标不精确的加或减5)是(98,473),(487,470),(969,471),(969,190)。正如您可以看到鼠标沿x轴或y轴越远,它变得越不准确。我尝试使用相同的方法捕获鼠标坐标,在小提琴中复制它,但我不能在那里复制它...还有一件事需要注意,可能很重要的是当我记录svg文档时,宽度和height设置为略小于视框值的值,即。给定视框值0 0 1400 700时,宽度为1380,高​​度为676。无论如何,这里是小提琴,所有的svg属性都与我们的程序相同。

The problem is with converting mouse click coordinates into the svg coordinates in the user space. I'm using the coordinates to drag a rectangle across the screen, and as the cursor gets further to the right in the svg space the coordinates become more and more skewed. To test this in a simple manner, I put three rectangles in global svg space at (100, 500), (500, 500), (1000, 500), and (1000, 200). Using a simple logging function the coordinates I receive(plus or minus 5 for mouse imprecision) are (98, 473), (487, 470), (969, 471), (969, 190). As you can see the further along the x or y axis the mouse goes, the more inaccurate it becomes. I tried to replicate this in a fiddle using the same method for capturing mouse coordinates, but I can't replicate it there... One more thing to note that may be significant is the fact that when I log the svg document, the width and height are set to values slightly less than the viewbox values, ie. 1380 width and 676 height given the viewbox value of "0 0 1400 700". Anyway, here's the fiddle, all the svg properties are the same as they are in my program.

http://jsfiddle.net/ASLma/11/

推荐答案

似乎问题是直接在浏览器中打开svg。相反,我通过embed标签将其嵌入到html页面中,并且效果很好。我不确定为什么这对我的鼠标坐标精度来说很重要,但解决方案是一个解决方案。

It seems the problem was opening the svg directly in the browser. Instead, I embedded it in an html page via an embed tag, and it works great. I'm not sure why that would matter in terms of my mouse coordinate accuracy, but a solution is a solution.

这篇关于SVG捕获鼠标坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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