0

所以我有一个画布,上面画着等距平铺图,看起来很完美。

在脚本底部的事件侦听器中,我在画布内抓取光标的坐标。我怎样才能找出光标悬停在哪个图块上?

var cs = document.getElementById('board');

var c = cs.getContext("2d")
var gridWidth=100
var gridHeight=50
var tilesX = 12, tilesY = 12;
var spriteWidth=gridWidth
var spriteHeight=img.height/img.width*gridWidth
cs.width = window.innerWidth //spriteWidth*10
cs.height = window.innerHeight //spriteHeight*10
var ox = cs.width/2-spriteWidth/2
var oy = (tilesY * gridHeight) / 2

window.onresize=function(){
cs.width = window.innerWidth //spriteWidth*10
cs.height = window.innerHeight //spriteHeight*10
ox = cs.width/2-spriteWidth/2
oy = (tilesY * gridHeight) / 2
draw()
}

draw();


function renderImage(x, y) {
c.drawImage(img, ox + (x - y) * spriteWidth/2, oy + (y + x) * gridHeight/2-(spriteHeight-gridHeight),spriteWidth,spriteHeight)
}

function draw(){
for(var x = 0; x < tilesX; x++) {
    for(var y = 0; y < tilesY; y++) {
        renderImage(x,y)
    }
}
}

cs.addEventListener('mousemove', function(evt) {
var x = evt.clientX,
y = evt.clientY;
console.log('Mouse position: ' + x + ',' + y);
}, false);

很抱歉粘贴了这么长的代码,但所有这些都只是为了放置等距网格。

编辑:另外,我怎样才能得到平铺图像的左上角坐标来中继它?

4

1 回答 1

0

假设您已将图块排列在最左列和最顶行为零的位置:

var column = parseInt(mouseX / tileWidth);

var row = parseInt(mouseY / tileHeight);

顺便说一句,如果您最终将画布从页面的左上角移开,那么您必须通过画布偏移量调整鼠标坐标。

以下是如何计算鼠标位置的示例:

// references to the canvas element and its context

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

// get the offset position of the canvas on the web page

var BB=canvas.getBoundingClientRect();
var offsetX=BB.left;
var offsetY=BB.top;

// listen for mousedown events

canvas.onmousedown=handleMousedown;

function handleMousedown(e){

     // tell the browser we will handle this event

     e.preventDefault();
     e.stopPropagation();

     // calculate the mouse position

     var mouseX=e.clientX-offsetX;
     var mouseY=e.clientY-offsetY;

}
于 2014-05-14T16:02:13.467 回答