如何在我的网格上记录X,Y鼠标位置?

时间:2014-10-31 14:13:09

标签: javascript jquery html5 canvas

我有这个脚本来创建矩形网格,我将如何记录鼠标位置的地图坐标,所以如果鼠标在1,1上它会记录1,1?:

+---+---+---+---+
|0,0|0,1|0,2|0,3|
+---+---+---+---+
|1,0|1,1|1,2|1,3|
+---+---+---+---+
|2,0|2,1|2,2|2,3|
+---+---+---+---+
|3,0|3,1|3,2|3,3|
+---+---+---+---+

这是我必须创建网格的脚本;

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = (32 * 12);
canvas.height = (32 * 12);
document.body.appendChild(canvas);

var posX = 0;
var posY = 0;
var tileSize = 32;

$(document).ready(function(){
    drawGrid();
});

function drawGrid(){
    for(var x = 0; x < 12; x++){
        for(var y = 0; y < 12; y++){
            ctx.rect(posX, posY, tileSize, tileSize);
            ctx.stroke();
            posX += tileSize;
        }
       posY += tileSize;
       posX = 0;
   }
}

2 个答案:

答案 0 :(得分:1)

例如,根据图块大小量化鼠标位置(假设您已经获得了鼠标位置):

var gridX = (mouseX / tileSize)|0;
var gridY = (mouseY / tileSize)|0;

现在,您可以将gridXgridY记录为原始网格定义。

答案 1 :(得分:0)

在鼠标移动时,获取鼠标的x和y位置并将其除以tileSize

Fiddle

上的演示
canvas.onmousemove = function(e) {
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  document.getElementsByTagName('div')[0].innerHTML = '(' + Math.floor(mouseX / tileSize) + ', ' + Math.floor(mouseY / tileSize) + ')';
}