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

时间:2011-04-22 01:21:58

标签: jquery canvas mootools scale mouse-position

我一直在尝试采用几个简单的MooTools操作的逻辑,并将其转换为与jQuery一起使用。

我想要的逻辑是jsfiddle它允许的是在css大小调整的画布元素上获得准确的鼠标位置。

我发现了answer here因此我已经工作了几个小时而无济于事

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

到目前为止,我用他的answer注释掉了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;

1 个答案:

答案 0 :(得分:10)

我使用普通的javascript做了一点demo。我有一个blog post解释过程。

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

相关问题