【问题标题】:How can canvas coordinates be converted into tile coordinates?如何将画布坐标转换为平铺坐标?
【发布时间】:2014-07-02 17:52:54
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 这是我对做常规 32x32 网格的人的回答,但也许您可以了解等距? stackoverflow.com/questions/23615605/… -- 它使用模数 (%)。我对 iso 网格一无所知,所以很遗憾,我无法提供进一步的帮助。
  • 你在别处说过'这不是工作',所以不要接受答案和/或问,@markE 既有知识又有善意。您可能想仔细查看我的帖子gamedev.stackexchange.com/questions/73859/…,因为结果很好,您可以轻松配置它。在你的路上,你可能不得不挖掘什么是转换矩阵和其他东西。最后(注释)代码在这里jsfiddle.net/gamealchemist/zF2w8
  • 谢谢@GameAlchemist。很抱歉让人们感到困惑。

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


【解决方案1】:

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

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;

}

【讨论】:

  • 那我可以直接用+ oy 来添加偏移量吗?
  • 我在答案中添加了一个示例,说明如何根据网页中的画布位置计算鼠标位置。
猜你喜欢
  • 2011-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-08
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 2019-08-24
相关资源
最近更新 更多