在 CSS 缩放的画布中获取正确的鼠标位置

3

我一直在试图将一对简单的 MooTools 操作的逻辑转换为适用于 jQuery 的逻辑。

我想要的逻辑是针对这个 jsfiddle ,它允许在使用 CSS 调整大小时精确获取画布元素上的鼠标位置。

我在 SO 上找到了答案,但尝试了几个小时也没有结果。

我认为我理解了他的逻辑,但由于某种原因我没有看到结果。

这是我根据 arby 的答案所做的工作,已经注释掉了。

// Get the change ratio for the new css set size
//var cssScale = [canvas.getSize().x / canvas.get('width'), canvas.getSize().y / canvas.get('height')];
var cssScale = [$('canvas').height() / $('canvas').attr('height'), $('canvas').width() / $('canvas').attr('$('canvas').height() / $('canvas').attr('height'),')]

//Create an object of the dimensions
// I think from my looking at the jsfiddle x&y is the position of the rect in his canvas
// and w&h are the height and width of that rect so it's not really necessary for my problem which
// is just getting mouse cords accuratly.
//this.setDims(x*cssScale[0], y*cssScale[1], w*cssScale[0], h*cssScale[1]);

// This is the offset of the clickable square in his code.
//this.offset = [x - this.dims[0], y - this.dims[1]];

// Now I do not know what this is
// If the offset is just for position in their code why is it used here
// How can you display just scaled mouse position
this.x = (x - this.offset[0]) / cssScale[0] + w * .5;
this.y = (y - this.offset[1]) / cssScale[1] + h * .5;

不确定您在设置cssScale行中尝试做什么。您正在将宽度除以高度属性除以高度属性,即1。即使如此,您也在由单引号分隔的字符串中使用单引号。这应该会导致语法错误。我猜您想要类似于var cssScale = [$('canvas').width() / $('canvas').attr('width'), $('canvas').height() / $('canvas').attr('height')]的东西。 - musaul
我不确定是否正在尝试将Mootools逻辑转换为jQuery,我认为正在发生的是您正在使用该行获取CSS增长/收缩的比率。 - austinbv
1个回答

10

我用原生JavaScript做了一个小的演示。我有一篇博客文章解释这个过程。

请仔细查看此示例,特别注意变量sxsy的使用位置。它们是缩放比例。您基本上需要将其应用于画布内的任何偏移量(即 屏幕中的鼠标位置 减去 画布偏移量)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接