Drag Ball Graphic 2

by Matthew Vasallo

HTML

<canvas id="myCanvas" height="900px" width="8000px" ></canvas>

JavaScript

$(document).ready(function() {

var canvas = $("#myCanvas");
var cxt = canvas.get(0).getContext("2d");

var canvasWidth = canvas.width();
var canvasHeight = canvas.height();

var balls=[];
var speedAnimate=40;
var speedMouse=50;
var figureNum=6000;
var mousePress=false;
var ballSelect=false;
var ballSelectNum;


var Ball =  function(x,y,vx,vy){
	this.x=x;
	this.y=y;
	this.vx=vx;
	this.vy=vy;	
	this.r=1;
	this.c="#FFED79";
	this.select=false;

	this.update = function(){
		if(!this.select){
			this.x += this.vx;
			this.y += this.vy;

			if(this.x>canvasWidth-this.r||this.x<this.r){this.vx*=-1};
			if(this.y<-this.r){this.y=canvasHeight+this.r};
		}

	}
	
	this.drawBall= function (){

		cxt.fillStyle=this.c;
		cxt.beginPath();
		cxt.arc(this.x,this.y,20,0,Math.PI*2,true);
		cxt.closePath();
		cxt.fill();
		cxt.globalAlpha = 0.7;
	}
}


var beginBall = function(x,y,vx,vy){

		balls.push(new Ball(x,y,vx,vy));}

		
var animate = function(){
	cxt.clearRect(0, 0, canvasWidth, canvasHeight);
	
	for(var i=0; i<figureNum; i++){
		balls[i].update();
		balls[i].drawBall();
	}

	setTimeout(animate, speedAnimate);
}

	$(canvas).mousedown(function(e){
	
		mousePress = true;
	
			for(var i=0;i<figureNum;i++){
			
					var distX=e.pageX-balls[i].x;
					var distY=e.pageY-balls[i].y;
					var distance = Math.sqrt((distX*distX)+(distY*distY));
				
					if(distance<=20){
						ballSelect=true;
						ballSelectNum=i;
						balls[i].select=true;
					
						break;
					}
				
					//else{balls[i].c="#FFED79";}

			}
	});
		
	$(canvas).mousemove(function(e){
		
		if(mousePress && ballSelect){
			balls[ballSelectNum].x=e.pageX;
			balls[ballSelectNum].y=e.pageY;
			balls[ballSelectNum].c="#F05133";
		}
	});
		
	
	$(canvas).mouseup(function(e){
		
		if(ballSelect){
		mousePress=false;
		ballSelect=false;

	
			balls[ballSelectNum].select=false;
			balls[ballSelectNum].c="#FFED79";
	
		}
	})
	




		cxt.fillRect(0, 0, canvasWidth, canvasHeight);
	
		for(var...