2014-05-14 106 views
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); 

對不起,粘貼這麼長的代碼,但它只是爲了放置等距網格。

編輯:另外,我怎麼能得到平鋪圖像的左上角座標來中繼它?

+1

這是一個答案我有別人做一個普通32×32格,但也許你可以得到等距的想法? http://stackoverflow.com/questions/23615605/where-in-the-grid-the-tile-belongs/23615674?noredirect=1#comment36256591_23615674 - 它使用模(%)。我不知道iso網格,所以我不能進一步幫助,不幸的是。 – ndugger

+1

你說別處沒有這個工作,所以不要接受答案和/或問,@ markE既有知識又有善意。您可能希望在我的帖子中查看近視http://gamedev.stackexchange.com/questions/73859/adapting-tilemap-algorithm-to-support-isometric-tilemap/73874#73874,因爲結果很好,而且您可以輕鬆配置它。在你的路上,你可能需要挖掘什麼是轉換矩陣和其他東西。最後(評論)代碼在這裏http://jsfiddle.net/gamealchemist/zF2w8/ – GameAlchemist

+0

謝謝@GameAlchemist。抱歉讓人困惑。 – ThePixelPony

回答

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; 

} 
+0

所以我只是'+ oy'來添加偏移量? – ThePixelPony

+1

我在答案中加入了一個基於畫布在網頁中的位置來計算鼠標位置的例子。 – markE