You could solve this by checking the color at the current mouse position. If it's black your most likely touching the X. Of course this will just work if there aren't any other black colors in your image so the better way is done using some math.
So first define the start and end points of your lines as individual points - this way we can use those for the calculation.
const pointA={x:0,y:0};
const pointB={x:100,y:100};
const pointC={x:100,y:0};
const pointD={x:0,y:100};
Now to check if you're on one of the lines those four points form you can use this formula:
var treshold=0.01;
var onFirstLine=distance(pointA, mousePosition) + distance(pointB, mousePosition)-distance(pointA, pointB)<treshold;
Here we're adding up the distances from pointA and pointB to the mouse position and if the result would be equal to the distance from pointA to pointB we've detected a hit.
The problem is we would need to hit it extremely precise that's why we're subtracting the distance and compare it to a treshold instead.
Here's the complete example:
const pointA={x:0,y:0};
const pointB={x:100,y:100};
const pointC={x:100,y:0};
const pointD={x:0,y:100};
function drawX(x, y) {
ctx.beginPath();
ctx.moveTo(pointA.x, pointA.y);
ctx.lineTo(pointB.x, pointB.y);
ctx.stroke();
ctx.moveTo(pointC.x, pointC.y);
ctx.lineTo(pointD.x, pointD.y)
ctx.stroke();
}
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
drawX();
function myFunction(e) {
var tempPoint = {
x: e.offsetX,
y: e.offsetY
};
var treshold = 0.01;
if (distance(pointA, tempPoint) + distance(pointB, tempPoint) - distance(pointA, pointB) < treshold || distance(pointC, tempPoint) + distance(pointD, tempPoint) - distance(pointC, pointD) < treshold) {
console.log("you're touching X")
} else {
console.log("you're NOT touching X")
}
}
function distance(locPointA, locPointB) {
return Math.sqrt(Math.pow(locPointB.x - locPointA.x, 2) + Math.pow(locPointB.y - locPointA.y, 2));
}
<canvas id="myCanvas" width="300" height="150" onmousemove="myFunction(event)" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>