简体   繁体   中英

How to “add” new balls on mouse click in JS HTML5 Canvas?

I've written code in HTML5 canvas where a ball drops from my cursor location no matter where I move it. Whenever I move it, it refreshes, and drops again from that location.

I'd like a new ball to appear every time I click the mouse, so that if I've clicked a few times, there are multiple balls that have been dropped. How would I go about doing this?

I know I need to utilize the eventlistener for click somehow, but in my attempts, nothing has worked. Any advice would be appreciated.

Here is the code:

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");


var W = window.innerWidth,
    H = window.innerHeight;
var running = false;

canvas.height = H; canvas.width = W;


var ball = {},
    gravity = .5,
    bounceFactor = .7;

ball = {
  x: W,
  y: H,

radius: 20,
color: "WHITE",


vx: 0,
vy: 1,

draw: function() {

    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, false);
    ctx.fillStyle = this.color;
    ctx.fill();
    ctx.closePath();
  }
};


function clearCanvas() {
  ctx.clearRect(0, 0, W, H);
}

function update() {
  clearCanvas();
  ball.draw();

ball.y += ball.vy;

ball.vy += gravity;
if(ball.y + ball.radius > H) {
    ball.y = H - ball.radius;
    ball.vy *= -bounceFactor;
  }
}


canvas.addEventListener("mousemove", function(e){
    ball.x = e.clientX;
    ball.y = e.clientY;
    ball.draw();
});
  setInterval(update, 1000/60);

ball.draw();

Seems to be a duplication of How do I add a simple onClick event handler to a canvas element?

Anyway, you can use the click event:

canvas.addEventListener('click', function(event) {
    ...
});

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