如何将画布坐标转换为平铺坐标?

时间:2014-05-14 15:13:41

标签: javascript html5 canvas html5-canvas mouse-coordinates

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

在脚本底部的事件监听器中,我抓住了画布内的光标坐标。我怎么能找出光标悬停在哪个区块上?

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);

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

编辑:另外,我怎样才能获得拼贴图像的左上角坐标来传递它?

1 个答案:

答案 0 :(得分: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;

}