簡體   English   中英

單擊時如何使圓圈消失(JavaScript |畫布)

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

我目前的問題是,頁面加載后根本沒有出現圓圈。 僅在單擊圓圈所在的位置時顯示,而在外部某處單擊時消失。 (鏈接到下面的小提琴)

我在“ addEventListener”方法中使用了“ mousedown”事件。 變量“距離”代表光標坐標和圓心之間的距離。

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);   

腳本的結果應如下所示:

  1. 頁面已加載
  2. 在左側可見圓圈
  3. 點擊圓圈,它消失了

這是小提琴: 小提琴 (單擊“鼠標位置= 100; 300”(或多或少)以查看圓圈)

提前致謝!!

您的代碼中有一些小故障:

  • 頁面加載時畫圓
  • 在writeMessage中,不要清除整個畫布(只清除消息)
  • 在mousedown中,使用clearRect清除圓圈

演示: http : //jsfiddle.net/m1erickson/LQ2ak/

加載后:在屏幕上繪制圓圈

// 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();

在writeMessage中:僅清除繪制消息的畫布

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

在mousedown中:查看鼠標是否在圓內。 如果是,請清除畫布。

// 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM