2011-04-22 247 views
3

我一直試圖採取幾個簡單的MooTools操作的邏輯,並將其轉換爲使用jQuery。在CSS縮放畫布中獲取正確的鼠標位置

我想要的邏輯就是爲了這個jsfiddle它允許的是通過css調整大小來在canvas元素上獲得準確的鼠標位置。

我發現answer here,所以我已經工作了幾個小時都無濟於事

我想我明白他的邏輯,但擬合由於某種原因,我沒有看到結果

這裏是我有什麼從他answer與阿拜的邏輯迄今所做註釋掉

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

不確定你在設置'cssScale'的行中想要做什麼。您將使用 - height屬性除以height屬性來劃分寬度 - 即1.即使這樣,您在由單引號分隔的字符串中也有單引號。這應該給你語法錯誤。我猜你想要'var cssScale = [$('canvas')。width()/ $('canvas')。attr('width'),$('canvas')。height()/$('canvas')。attr('height')]' – musaul 2011-04-24 18:29:42

+0

我不是100%肯定要麼我試圖將mootools邏輯轉換爲jquery,我認爲正在發生的是你得到的css增長率/收縮這條線 – austinbv 2011-04-24 18:31:29

回答

10

我用普通的JavaScript了一個小demo。我有一個blog post解釋過程。

查看示例,特別注意使用變量sxsy的位置。他們是你的縮放比例。您基本上需要將此應用於畫布內的任何偏移量(即屏幕上的鼠標位置減去畫布偏移量)。