I am trying to make a JavaScript version of buttons I initially created in Objective C. The approach involves creating two functions. The first draws five circles on a canvas and saves their centre coordinates. The second compares circle coordinates with coordinates of each mouse click and uses Pythagoras' theorem to detect whether an event happens within one of the five circles.
EDIT
Paragraph previously read
The problem is that circles produced by the drawing function are visible if each function is put in separate scripts. But somehow they vanish from the canvas altogether if I put both functions in the same script (i.e. by commenting out lines 52-53 in jsfiddle). The problem appears when I introduce the second function but I don't understand why.
Thanks to Bashu's answer two syntax issues have now been addressed successfully. The original question has been changed to reflect this. The code in jsfiddle shows both functions running together in the same script with function(e)
displaying a clickRing
where the mouse clicks on the canvas and correctly identifying each button. The code example now includes some missing mouse initialisation that had stopped mouse clicks from successfully drawing a clickRing
.
Here is the second function.
<script>
const mouse = document.getElementById('canvas');
var ctx2 = mouse.getContext('2d');
var x2; // click x
var y2; // click y
var clickRing = function(e){
x2 = e.offsetX - hCentre;
y2 = e.offsetY - vCentre;
var clickRadius = buttonRadius * 0.85; // clear button boundary
// show all Mouse hits including misses and near misses
ctx2.beginPath();
ctx2.arc(x2, y2, clickRadius * 0.85, 0, Math.PI*2);
ctx2.strokeStyle = "black";
ctx2.stroke();
for (i = 0; i < numberOfButtons; i++) {
x1 = xButtonCoords[i];
y1 = yButtonCoords[i];
// ctx1 ctx2
var xSquared = Math.pow((x1 - x2),2);
var ySquared = Math.pow((y1 - y2),2);
// find distance from button centre coordinates to clickpoint
var hypotenuse = Math.sqrt(xSquared + ySquared);
var distance = parseFloat(hypotenuse).toFixed(0);
if (distance < (buttonRadius - clickRadius)) {
alert("button : "+(i+1)+"\n"+
"distance from centre to Mouse : "+distance);
}
}
}
document.addEventListener('mousedown', clickRing);
</script>
Here is the entire code in jsfiddle.
I am new to Javascript and am searching here, here, here and here trying to learn more about DOM but so far nothing gives me a clue what to try next. I welcome suggestions. Thanks in advance.