0

I'm trying to make something similar to osu where I can click on a disc and a new one pops up. Right now, whenever I click anywhere on the canvas a new disc appears and the old one is cleared. I need it to only happen when I click on the current disc. How can I accomplish this? To clarify it a bit, there will only be one disc on the screen at a time. Whenever I click on it, the canvas will be cleared and a new disc will be created on the canvas at random coordinates.

This is my javascript code so far:

var elem = document.getElementById('myCanvas');
elem.onclick = function(){ 
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.clearRect(0,0,1000,750);

    ctx.beginPath();
    var posx = Math.floor(Math.random() * 950);
    var posy = Math.floor(Math.random() * 625)
    ctx.arc(posx+25, posy+25, 25, 0, 2 * Math.PI);
    ctx.stroke();
    var myColors = ['blue', 'red', 'green', 'yellow', 'black', 'maroon'];
    var selectedcolor = myColors[Math.floor(Math.random() * myColors.length)];
    ctx.fillStyle = selectedcolor;
    ctx.fill();
}
Esjee
  • 25
  • 7
  • Could you clarify exactly what you want to happen. If the user clicks on a disk you want a new one to pop up, but where does it pop up? And can the user then click on either disk and a third one pops up? Also, do you have to use canvas - if can be done but it gets a bit messy finding out what object you are in given canvas has no concept of 'object', especially when they overlap each other. – A Haworth May 26 '21 at 06:23
  • In your onclick code you are not getting the mouse coordinates, get them and then check if the position is in your disk – Helder Sepulveda May 26 '21 at 13:26
  • Does this answer your question? [How do I get the coordinates of a mouse click on a canvas element?](https://stackoverflow.com/questions/55677/how-do-i-get-the-coordinates-of-a-mouse-click-on-a-canvas-element) – Helder Sepulveda May 26 '21 at 13:27

0 Answers0