Dejo por acá la versión realizada para esta práctica:
<canvas width="600" height="400"></canvas>
<script>
const d = document
var $canvas = d.querySelector("canvas")
var brush = $canvas.getContext("2d")
let canvasW = $canvas.getAttribute("width")
let canvasH = $canvas.getAttribute("height")
brush.fillStyle = "lightgray"
brush.fillRect(0, 0, canvasW, canvasH)
function drawCircle(xPoint, yPoint, radius, fill) {
let fullAngle = 2 * Math.PI
brush.fillStyle = fill
brush.beginPath()
brush.arc(xPoint, yPoint, radius, 0, fullAngle)
brush.fill()
}
function getRandom(maxMeasure, maxRadius) {
random = Math.round(Math.random() * maxMeasure)
if(random < maxRadius) {
random = random + (maxRadius - random)
return random
} else if(random > (maxMeasure - maxRadius)) {
random = random - (random - (maxMeasure - maxRadius))
return random
} return random
}
function cleanCanvas() {
brush.clearRect(0, 0, canvasW, canvasH)
}
function drawRandomTarget() {
cleanCanvas()
brush.fillStyle = "lightgray"
brush.fillRect(0 , 0, canvasW, canvasH)
xRandom = getRandom(canvasW, maxRadius)
yRandom = getRandom(canvasH, maxRadius)
drawCircle(xRandom, yRandom, maxRadius, "red")
drawCircle(xRandom, yRandom, middleRadius, "white")
drawCircle(xRandom, yRandom, smallRadius, "red")
}
let maxRadius = 30
let middleRadius = maxRadius - 10
let smallRadius = maxRadius - 20
let xRandom
let yRandom
setInterval(drawRandomTarget, 1000)
$canvas.addEventListener("click", (e) => {
let xClick = e.offsetX
let yClick = e.offsetY
let maxLeftX = xRandom - smallRadius
let maxRightX = xRandom + smallRadius
let maxTopY = yRandom - smallRadius
let maxBottomY = yRandom + smallRadius
if((xClick < maxRightX) && (xClick > maxLeftX) && (yClick < maxBottomY) && (yClick > maxTopY)) {
alert("¡¡¡Haz dado en el blanco!!!")
}
})
</script>