+1 vote
by
isPointInPath() only triggers on the top tile when hovering the mouse, and all other tiles are highlighted.
5fa056d1a428d445666886.jpeg

When you hover your cursor over the bottom half, nothing stands out (all remain black)
5fa056d9e6e46210539607.jpeg
window.onload = function() {
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = canvas.width = window.innerWidth,
height = canvas.height = window.innerHeight,
tileWidth = 60,
tileHeight = 30


ctx.translate(width / 2, 50)

var img = document.createElement("img")

img.addEventListener("load", function() {

draw()

})

img.src = "tileset.png"

function draw() {

for(var x = 0; x < 1; x++) {
for(var y = 0; y < 2; y++) {
drawImageTile(x, y, Math.floor(Math.random() * 16))

}
}
}


let rectFigure = new Path2D()
rectFigure.moveTo(0, 0)
rectFigure.lineTo(tileWidth / 2, tileHeight / 2)
rectFigure.lineTo(0, tileHeight)
rectFigure.lineTo(-tileWidth / 2, tileHeight / 2)



function drawImageTile(x, y, index) {

this.x = (x - y) * tileWidth/2
this.y = (x + y) * tileHeight/2
this.index = index

ctx.save();
ctx.translate(this.x, this.y);



if(cycleX != 'off' && cycleY != 'off'){


ctx.beginPath()
ctx.fillStyle = 'red';
ctx.fill(rectFigure);
ctx.closePath()


}else{
ctx.beginPath()
ctx.fillStyle = 'black';
ctx.fill(rectFigure);
ctx.closePath()
}



ctx.restore();
}


var cycleX = 'off',
cycleY = 'off'

canvas.addEventListener('mousemove', function(e){

if (ctx.isPointInPath(rectFigure, e.clientX, e.clientY)) {

cycleX = e.clientX - width / 2
cycleY = e.clientY - 50


}else{

cycleX = 'off'
cycleY = 'off'

}


})

canvas.onmouseout = function(e){

cycleX = 'off'
cycleY = 'off'
}

setInterval(()=>{

ctx.clearRect(-500, -500, 1000, 1000)
draw()

},500)




}
I want to get an independent selection of the tile on which the cursor is pointing, and to be colored red

2 Answers

0 votes
by
 
Best answer
snippet
...