var wd, cvs, ctx, r, timer, num; var x = [], y = [], v = [], cl = []; wd = 500; r = 20; num = 0; onload = function() { cvs = document.getElementById("Canvas"); ctx = cvs.getContext("2d"); cvs.height = wd; cvs.width = wd; ctx.globalAlpha = 0.9; ctx.globalCompositeOparation = "source-over"; cvs.onclick = setBall; setInterval(f, 10); } function f() { if (num == 0) {return;} ctx.clearRect(0, 0, wd, wd); for(var i = 0; i < num; i++) { ctx.beginPath(); ctx.fillStyle = cl[i]; ctx.arc(x[i], y[i], r, 0, Math.PI * 2); ctx.fill(); x[i] += v[i][0]; y[i] += v[i][1]; if (x[i] >= wd - r || x[i] <= r) {v[i][0] = -v[i][0];} else if (y[i] >= wd - r || y[i] <= r) {v[i][1] = -v[i][1];} } } function setBall(e) { var x1, y1; x1 = e.pageX - cvs.offsetLeft; y1 = e.pageY - cvs.offsetTop; if (x1 <= r || x1 >= wd - r || y1 <= r || y1 >= wd - r) {return;} num++; x[num - 1] = x1; y[num - 1] = y1; v[num - 1] = [(Math.random() * 2 + 2) * (Math.random() - 0.5) * 2, (Math.random() * 2 + 2) * (Math.random() - 0.5) * 2]; cl[num - 1] = "rgb(" + rnd() + "," + rnd() + "," + rnd() + ")"; } function rnd() { return String(Math.floor(Math.random()*256)); } function cvsClear() { ctx.clearRect(0, 0, wd, wd); num = 0; }