Why does the isPointInPath function fail on the second tile in the Canvas?
-
isPointInPath ()
only fires on the top tile on mouse hover, and all other tiles are selected.
When hovering over the bottom tile, nothing is selected (everything remains black)
I want to get independent selection of the tile on which the cursor is hovering, and colored in redwindow.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) }
JavaScript Anonymous, Mar 2, 2020 -
Sophie Baxter
-
https://jsfiddle.net/dpablo_escobarr/o1kepxb2/Lydia Cabrera
2 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!