Javascript 是否可以检测画布上单击的位置并在单击后删除项目?

Javascript 是否可以检测画布上单击的位置并在单击后删除项目?,javascript,html,canvas,Javascript,Html,Canvas,我有一组javascript代码,它创建一个圆形对象,然后将其推送到画布上。有没有一种方法可以让用户单击其中一个圆圈时,对象会消失? 这是我的Javascript代码 // get a reference to the canvas and its context var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); // set canvas to equal window size

我有一组javascript代码,它创建一个圆形对象,然后将其推送到画布上。有没有一种方法可以让用户单击其中一个圆圈时,对象会消失? 这是我的Javascript代码

// get a reference to the canvas and its context
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// set canvas to equal window size
window.addEventListener('resize', resizeCanvas, false);

// newly spawned objects start at Y=25
var spawnLineY = 25;

// spawn a new object every 1500ms
var spawnRate = 1500;

// when was the last object spawned
var lastSpawn = -1;

// this array holds all spawned object
var objects = [];

// save the starting time (used to calc elapsed time)
var startTime = Date.now();

// start animating
animate();

function resizeCanvas() {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        /**
         * Your drawings need to be inside this function otherwise they will 
be reset when 
         * you resize the browser window and the canvas goes will be cleared.
         */
}
function spawnRandomObject() {

// select a random type for this new object
var t;

// About Math.random()
// Math.random() generates a semi-random number
// between 0-1. So to randomly decide if the next object
// will be A or B, we say if the random# is 0-.49 we
// create A and if the random# is .50-1.00 we create B
var random;
random = Math.random();
if (random < 0.75 && random > .50) {
    t = "red";
} else if (random > .75) {
    t = "blue";
} else if (random < .50 && random > .25) {
    t = "purple"
} else if (random < .25) {
    t = "green"
}

// create the new object
var object = {

    // set this objects type
    type: t,
    // set x randomly but at least 15px off the canvas edges
    x: Math.random() * (canvas.width - 30) + 15,
    // set y to start on the line where objects are spawned
    y: spawnLineY,
    downspeed: Math.floor((Math.random() * 100) + 5)/100,
    radius: Math.floor((Math.random() * 175) + 5),
    onclick : alert('blah'),
}

// add the new object to the objects[] array
objects.push(object);
}
// the code to make the circle disappear would go here
popBalloon()


function animate() {

// get the elapsed time
var time = Date.now();

// see if its time to spawn a new object
if (time > (lastSpawn + spawnRate)) {
    lastSpawn = time;
    spawnRandomObject();
}

// request another animation frame
requestAnimationFrame(animate);

// clear the canvas so all objects can be 
// redrawn in new positions
ctx.clearRect(0, 0, canvas.width, canvas.height);

// draw the line where new objects are spawned
ctx.beginPath();
ctx.moveTo(0, spawnLineY);
ctx.lineTo(canvas.width, spawnLineY);
ctx.stroke();
// move each object down the canvas
for (var i = 0; i < objects.length; i++) {
    var object = objects[i];
    object.y += object.downspeed;
    ctx.beginPath();
    ctx.arc(object.x, object.y, object.radius, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fillStyle = object.type;
    ctx.fill();
}

}
resizeCanvas();

我不完全确定如何获得鼠标的x和y位置,但如果你能得到,这个函数应该有助于检测碰撞

function checkColision()// if mouse collides with object
{
for (var i = 0; i < objects.length; i++)
{
     // get the distance between mouse and object
    var xRange = Math.abs(mouse.x - object[i].x);//abslute value so no negative numbers
    var yRange = Math.abs(mouse.y - object[i].y);

    if (xRange < MIN_COLISION_RANGE && yRange < MIN_COLISION_RANGE)
    {
        object.splice(i, 1);//remove object
        i--;//go back one iteration
    }
}
}

要获取画布上的鼠标单击位置

// assuming canvas is already defined and references an DOM canvas Element
const mouse = {x ;0,y :0, clicked : false};
function mouseClickEvent(event){
    mouse.x = event.offsetX;
    mouse.y = event.offsetY;
    mouse.clicked = true;
}
canvas.addEventListener("click",mouseClickEvent);
然后在渲染循环中检查鼠标单击

if(mouse.clicked){
      // do what is needed
    mouse.clicked = false; /// clear the clicked flag
}
确定点是否在圆内的步骤

// points is {x,y}
// circle is {x,y,r} where r is radius
// returns true if point touches circle
function isPointInCircle(point,circle){
     var x = point.x - circle.x;
     var y = point.y - circle.y;
     return Math.sqrt(x * x + y * y) <= circle.r;
}
或者使用ES6

function isPointInCircle(point,circle){
     return Math.hypot(point.x - circle.x, point.y - circle.y) <= circle.r;
}

我来试试。你需要自己得到最小碰撞范围,如果你用的是圆,它就是圆的半径。为了得到鼠标x和y,显然你可以只做e.clientX,e.ClientI在我最后的评论中犯了一个错误,如果最小碰撞范围是圆的半径,你必须将圆x和y设置为圆的中心,因为x和y是从对象的左上角开始的,我得到的错误是鼠标没有定义。有什么想法吗?