javascript - How to "add" new balls on mouse click in JS HTML5 Canvas? -
i've written code in html5 canvas ball drops cursor location no matter move it. whenever move it, refreshes, , drops again location.
i'd new ball appear every time click mouse, if i've clicked few times, there multiple balls have been dropped. how go doing this?
i know need utilize eventlistener click somehow, in attempts, nothing has worked. advice appreciated.
here 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 duplication of how add simple onclick event handler canvas element?
anyway, can use click
event:
canvas.addeventlistener('click', function(event) { ... });
Comments
Post a Comment