html 5のcanvas図面でスクロールするボールを実現

2306 ワード

<canvas id="canvas" width="800" height="300" style="border:1px solid #eeeeee;">
         &lt;canvas&gt;  ,    Chrome        FireFox    
</canvas>

  :<input type="range" min="1" max="100" onchange="colorChange(event,0)"/>

<script type="text/javascript"> 
 var context2D;   //    (0,0)    ,      2,      3 
var colors = "#357ec2,#ec594b,#fcd208,#4ab348";
var objectNum = 10;

 function draw(){

	context2D.clearRect(0, 0, canvas.width, canvas.height);   //      canvas   


	//context2D.fillStyle = '#666666'; 
	context2D.beginPath(); 

	for(i=1;i<=objectNum;i++)
	{
		itemInfo = sessionStorage.getItem('ball_'+i);

		items = itemInfo.split('_');
		x = parseInt(items[0]);
		y = parseInt(items[1]);
		dx = parseInt(items[2]);
		dy = parseInt(items[3]);
		color = items[4];

		context2D.fillStyle = color; 
		context2D.arc(x,y,20,0,Math.PI*2,true); 

		//      ,   dx/dy     x/y       。
		if (x + dx > canvas.width || x + dx < 0) dx = -dx; 
		if (y + dy > canvas.height || y + dy < 0) dy = -dy; 
		 
		x += dx;
		y += dy;

		sessionStorage.setItem('ball_'+i, x+"_"+y+"_"+dx+"_"+dy+"_"+color);       
		
	}

	context2D.fill();
 }

window.onload = function (){  
	var canvas = document.getElementById('canvas'); 
	context2D = canvas.getContext('2d'); 
	var c = colors.split(",");

	for(i=1;i<=objectNum;i++)
	{
		startX = parseInt(canvas.width*Math.random());
		startY = parseInt(canvas.height*Math.random());
		sx = parseInt(10*Math.random());
		sy = parseInt(10*Math.random());

		color = c[parseInt(c.length*Math.random())];
		sessionStorage.setItem('ball_'+i, startX+"_"+startY+"_"+sx+"_"+sy+"_"+color);       
	}

	setInterval(draw, 20);     //         20   
} 
 </script>