Colliding Balls Animation   #


<html> <body> <canvas id="mycanvas"></canvas> <script> var canvas = document.getElementById('mycanvas'); var ctx = canvas.getContext('2d'); canvas.width=900; canvas.height=900; var sizes = []; var colors = []; var lives = []; var cx = []; var cy = []; var color; var size=0; var xslope = []; var yslope = []; var tx = 0; var ty = 0; var x = 0; // let circleEnd = new Audio("dead.mp3"); // circleEnd.load(); var x=0; var y=0; var c = 0; // functions var mouseIsDown = false; function drawBall(x,y,color,radius) { ctx.beginPath(); counterClockwise=false; startAngle=Math.PI*0; endAngle=Math.PI*2; ctx.arc(x,y,radius,startAngle,endAngle,counterClockwise) ctx.fillStyle = color; ctx.lineWidth = 1; ctx.strokeStyle = color ctx.stroke() ctx.fill() } let start = setInterval(animate,15) function animate() { ctx.clearRect(0,0,canvas.width,canvas.height) for (var i=0; i<colors.length; i++) { if (cx[i]<=50 || cx[i]>=800) { xslope[i] = -xslope[i]; lives[i]--; } if (cy[i]<=50 || cy[i]>=800) { yslope[i] = -yslope[i]; lives[i]--; } if (lives[i]<=0) { // colors[i]="white"; // circleEnd.play(); cx.splice(i,1); cy.splice(i,1); xslope.splice(i,1); yslope.splice(i,1); lives.splice(i,1); colors.splice(i,1); sizes.splice(i,1); } cx[i]+=xslope[i]; cy[i]+=yslope[i]; drawBall(cx[i],cy[i],colors[i],sizes[i]); ctx.fillStyle = "black"; ctx.fillText(lives[i],cx[i],cy[i]); } } function mouseClick(e) { getCursorPosition(canvas,e); console.log("x: " + x + " y: " + y); cx.push(x); cy.push(y); lives.push(5); c = Math.floor(Math.random() * 3); if (c==0) { colors.push("red") color = "red" } else if (c==1) { colors.push("blue") color = "blue" } else { colors.push("green") color = "green" } size = Math.floor(Math.random() * 8)+10; sizes.push(size); xslope.push(Math.floor(Math.random() * 4)+1); yslope.push(Math.floor(Math.random() * 4)+1); drawBall(x,y,color,size); } function getCursorPosition(canvas, event) { var rect = canvas.getBoundingClientRect(); x = event.clientX - rect.left; y = event.clientY - rect.top; } canvas.onmousedown = function(e){ mouseIsDown = true; } canvas.onmouseup = function(e){ if(mouseIsDown) mouseClick(e); mouseIsDown = false; } canvas.onmousemove = function(e){ getCursorPosition(canvas,e); if(!mouseIsDown) return; return false; } </script> </body> </html>

Loading Please Wait...