2013-12-14 32 views
0

我知道這是一個簡單的計算,但你能幫助我嗎?試圖讓我的點對點遊戲'對齊'最近的點

Here's the fiddle

var canvas = document.getElementById('myCanvas'); 
var context = canvas.getContext('2d'); 
var radius = 4; 

for (x=radius; x<canvas.width-radius; x+=50) { 
    for (y=radius; y<canvas.height-radius; y+=50) { 
     context.beginPath(); 
     context.arc(x, y, radius, 0, 2 * Math.PI, false); 
     context.stroke(); 
    } 
} 
$('canvas').click(canvasClicked); 

function canvasClicked(e) { 
    var x = e.pageX - $(this).offset().left; 
    var y = e.pageY - $(this).offset().top; 
    context.beginPath(); 
    context.arc(x, y, radius, 0, 2 * Math.PI, false); 
    context.fillStyle = 'black'; 
    context.fill(); 
    context.lineWidth = 1; 
    context.strokeStyle = '#000000'; 
    context.stroke(); 
}; 

我想確定哪個cirlce是最接近用戶點擊的那個。

回答

3

答案就在這裏:

var newX = Math.round(x/50)*50 + radius; 
var newY = Math.round(y/50)*50 + radius; 
x = newX; 
y = newY; 

下面是該琴: http://jsfiddle.net/avall/vtEER/1/

您全面點擊位置你點發生器的分辨率;

哦,你應該注意邊緣點 - 對於

+0

我想你把錯誤的鏈接沒有做ifs。 – GameAlchemist

+0

對,我把錯誤的鏈接,該死的:)。編輯。 – avall

+0

美麗!非常感謝你。我在一個計算機實驗室教書,並且我會在演講中給大家展示這個點對點的遊戲,給學生一個他們可以玩的共同遊戲。 –