在CSS缩放的画布中获得正确的鼠标位置 [英] Getting correct mouse position in a CSS scaled canvas

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

问题描述

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

I have been trying to take the logic of a couple simple MooTools operations and convert it to work with jQuery.

我想要的逻辑是为这 jsfiddle 它允许的是通过css调整大小来获得在canvas元素上的精确鼠标位置。

The logic I want is for this jsfiddle what it allows is to get accurate mouse position on a canvas element with css resizing.

我发现回答这里我已经工作了几个小时没有效果

I found the answer here on SO I have been working for a couple hours with no avail

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

I think I understand his logic but fitting for some reason I am not seeing results

这是我到目前为止使用arby的逻辑从他的 answer 已注释掉

Here is what I have done so far with arby's logic from his answer commented out

// 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;


推荐答案

我做了一些 demo 使用纯javascript。我有一个博客文章介绍了该过程。

I've made a little demo using plain javascript. I've got a blog post explaning the process.

看看这个例子特别注意到变量 sx sy 正在使用。它们是你的缩放比例。您基本上需要将其应用于画布中的任何偏移(即鼠标位置在屏幕中减去画布偏移)。

Take a look at the example with special note to where the variables sx and sy are being used. They're your scaling ratio. You'll basically need to apply this to any offsets within the canvas (i.e. mouse position in the screen minus the canvas offset).

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

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