如何将画布坐标转换为tile坐标
How can canvas coordinates be converted into tile 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);
很抱歉粘贴了这么长的代码,但所有这些都只是为了铺设等距网格。
编辑:另外,我怎么能得到左上角的坐标平铺图像中继它?
假设您已经安排了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;
}
相关文章:
- 将event.offsetX和event.offset Y的坐标转换为webGL本机坐标
- OpenLayers:自动将 EPSG 4326 - 文本图层的坐标转换为地图的投影 (EPSG:900913)
- 将 GPS 坐标转换为距离,并以十进制度为单位将距离转换为半径
- 将 GeoJSON 坐标转换为其他投影以用于草坪.js
- 将位置坐标转换为画布坐标
- 如何将像素坐标转换为等轴测网格坐标
- Pixi.js / WebGL方法,用于将数据模型坐标转换为画布像素坐标
- 将坐标转换为阵列中的块位置
- 将lat/lng坐标转换为给定地图上的像素(使用JavaScript)
- 如何从(x, y)屏幕坐标转换为LatLng(谷歌地图)
- 如何将屏幕坐标转换为z变换元素上的坐标
- 在ThreeJS中将2D鼠标坐标转换为世界XZ坐标
- 将经纬度坐标转换为图像地图坐标
- 天文坐标转换的Bug
- HTML5地理定位将当前GPS位置的长宽坐标转换为一个变量
- 反向地理编码:将GPS坐标转换为位置名称的函数调用永远不会执行
- 将贴图的xyz坐标转换为经度/纬度
- 如何将画布坐标转换为tile坐标
- 将上/左偏移坐标转换为日/时间
- 如何转换“正常”"坐标转换为OpenLayers中的OSM坐标