Canvas - 通过变换等距视图,确定鼠标在哪个图块上
Canvas - Isometric view by transform, determine which tile is mouse on
当 canvas 转换时,我正在尝试在图块上实际悬停。
Problem image
What is working
渲染函数:
ctx.save()
ctx.transform(1, 0.5, -1, 0.5, 250, 150)
// ctx.setTransform(1, 0.5, -1, 0.5, 250, 150)
Terrain.forEach((line, lineNumber) => {
line.forEach((tile, blockNumber) => {
const block = new Block({
...resolveBlock(tile),
position: {
x: blockNumber * 32 + 250,
y: lineNumber * 32
},
size: {
width: 32,
height: 32
}
})
// check if the mouse position is on tile
block.mousePos(frameNow)
block.render()
})
})
ctx.restore()
正在处理的mousePos函数
ctx.rotate(Math.PI / 4)
但不是完整的 ctx.transform(...) 甚至 ctx.scale(1, 0.5)
function mousePos() {
let currentX =
mousePos.x * Math.cos(-(Math.PI / 4)) -
mousePos.y * Math.sin(-(Math.PI / 4))
let currentY =
mousePos.x * Math.sin(-(Math.PI / 4)) +
mousePos.y * Math.cos(-(Math.PI / 4))
if (
currentX >= this.position.x &&
currentX <= this.position.x + this.size.width - 1 &&
currentY >= this.position.y &&
currentY <= this.position.y + this.size.height - 1
) { // change color of hovered tile... }
}
感谢您的宝贵时间。
经过一番头脑风暴找到了解决方案;变换后找到鼠标位置
const invertedTransform = ctx.mozCurrentTransformInverse()
// sadly there is no currentTransformInverse in all browsers yet
const wX =
mousePos.x * invertedTransform.a +
mousePos.y +
invertedTransform.c +
invertedTransform.e
const wY =
mousePos.x * invertedTransform.b +
mousePos.y +
invertedTransform.d +
invertedTransform.f
当 canvas 转换时,我正在尝试在图块上实际悬停。
Problem image
What is working
渲染函数:
ctx.save()
ctx.transform(1, 0.5, -1, 0.5, 250, 150)
// ctx.setTransform(1, 0.5, -1, 0.5, 250, 150)
Terrain.forEach((line, lineNumber) => {
line.forEach((tile, blockNumber) => {
const block = new Block({
...resolveBlock(tile),
position: {
x: blockNumber * 32 + 250,
y: lineNumber * 32
},
size: {
width: 32,
height: 32
}
})
// check if the mouse position is on tile
block.mousePos(frameNow)
block.render()
})
})
ctx.restore()
正在处理的mousePos函数
ctx.rotate(Math.PI / 4)
但不是完整的 ctx.transform(...) 甚至 ctx.scale(1, 0.5)
function mousePos() {
let currentX =
mousePos.x * Math.cos(-(Math.PI / 4)) -
mousePos.y * Math.sin(-(Math.PI / 4))
let currentY =
mousePos.x * Math.sin(-(Math.PI / 4)) +
mousePos.y * Math.cos(-(Math.PI / 4))
if (
currentX >= this.position.x &&
currentX <= this.position.x + this.size.width - 1 &&
currentY >= this.position.y &&
currentY <= this.position.y + this.size.height - 1
) { // change color of hovered tile... }
}
感谢您的宝贵时间。
经过一番头脑风暴找到了解决方案;变换后找到鼠标位置
const invertedTransform = ctx.mozCurrentTransformInverse()
// sadly there is no currentTransformInverse in all browsers yet
const wX =
mousePos.x * invertedTransform.a +
mousePos.y +
invertedTransform.c +
invertedTransform.e
const wY =
mousePos.x * invertedTransform.b +
mousePos.y +
invertedTransform.d +
invertedTransform.f