Answer the question
In order to leave comments, you need to log in
Why doesn't the isPointInPath function work on the second tile in Canvas?
isPointInPath()
only fires on the top tile on hover, and all other tiles are selected.
When you hover over the bottom tile, nothing is highlighted (everything remains black)
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 independent selection of the tile on which the cursor is hovering, and be painted red
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question