[英]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);
腳本的結果應如下所示:
這是小提琴: 小提琴 (單擊“鼠標位置= 100; 300”(或多或少)以查看圓圈)
提前致謝!!
您的代碼中有一些小故障:
演示: 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.