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

时间:2017-05-08 22:58:27

标签: javascript html5 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
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();

3 个答案:

答案 0 :(得分:1)

获取画布上的鼠标点击位置

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

答案 1 :(得分:0)

我不完全确定如何获得鼠标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
    }
}
}

答案 2 :(得分:0)

如果是圆圈,使用Pythagorean theorem进行距离计算可能会有所帮助,因为可以使用通用案例CanvasRenderingContext2D.isPointInPath。只需“绘制”事件处理程序中的路径,但不要填充它,检查鼠标指针是否在内部。