如何将画布坐标转换为tile坐标

How can canvas coordinates be converted into tile coordinates?

本文关键字:坐标 转换 tile 布坐标      更新时间:2023-09-26

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

在脚本底部的事件侦听器中,我在画布中获取光标的坐标。我怎样才能知道光标在哪个贴图上悬停?

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

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

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

假设您已经安排了tile,其中最左边的列和最上面的行为零:

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