简体   繁体   中英

How to make the circle disappear when clicked (JavaScript | canvas)

my problem at the moment is that the circle does not appear at all when the page is loaded. It only appears when clicked on the place where the circle is and disappears when clicked somewhere outside. (link to the fiddle below)

I used 'mousedown' event in 'addEventListener' method. Variable 'distance' stands for the distance between the coordinates of cursor and the circle center.

canvas.addEventListener('mousedown', function(evt) {

    mousePos = getMousePos(canvas, evt);
    var distance = Math.sqrt( Math.pow((mousePos.x - 100), 2) + Math.pow((mousePos.y - 300), 2) ) ;

    if (distance <= 50 && distance >= 0) {
        console.log('clicked on the circle');
    }

}, false);   

The result of the script should go like this:

  1. page is loaded
  2. circle is visible on the left side
  3. clicked on the circle and it dissapears

Here's fiddle: fiddle (click at 'mouse position = 100; 300'[more or less] to see the circle)

Thanks in advance!!

A few glitches in your code:

  • draw the circle when the page loads
  • in writeMessage, don't clear the entire canvas (just clear the message)
  • in mousedown, clear the circle using clearRect

A Demo: http://jsfiddle.net/m1erickson/LQ2ak/

After onload: draw the circle on the screen

// define the circle
// (we need this info for hit-testing later)
var cx=100;
var cy=300;
var radius=50;

// draw the circle so it appears onload
context.arc(cx,cy,radius,0, 2*Math.PI);
context.closePath();  // this makes a closed circle instead of 360 arc
context.fillStyle = 'green';
context.fill();
context.strokeStyle = 'green';
context.stroke();

In writeMessage: only clear the canvas where the message is being drawn

context.clearRect(0, 0, canvas.width, 25);

In mousedown: see if the mouse is inside the circle. If yes, clear the canvas.

// hit-test the circle
// this method does not use "expensive" Math.sqrt
function mouseIsInsideCircle(mouseX,mouseY,cx,cy,radius){
    var dx=mouseX-cx;
    var dy=mouseY-cy;
    return(dx*dx+dy*dy<=radius*radius);
}

canvas.addEventListener('mousedown', function(evt) {

    var mousePos = getMousePos(canvas, evt);
    var mouseX=mousePos.x;
    var mouseY=mousePos.y;

    // if the mouse is inside the circle
    if(mouseIsInsideCircle(mouseX,mouseY,cx,cy,radius)){
        // erase the canvas
        context.clearRect(0,25,canvas.width,canvas.height);
    }

}, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM