试图让我的点对点游戏'捕捉到'最近的点

Trying to get my dot-to-dot game to 'snap to' the closest dot

本文关键字:最近 点对点 游戏 我的      更新时间:2023-09-26

我知道这是一个简单的计算,但你能帮我吗?

这是小提琴。

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是最接近用户点击位置的cirlce。

答案在这里:

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/

您将单击的位置四舍五入到点生成器的分辨率;

哦,你应该注意边缘点-没有为做ifs