SOURCE

console 命令行工具 X clear

                    
>
console
var boxx = 30;  //盒子X坐标
var boxy = 20;  //盒子Y坐标
var boxWidth = 350; //盒子宽度
var boxHeight = 250; //盒子高度
var ballx = 100;		//小球X坐标
var bally = 60;		//小球Y坐标
var ballRadius = 10;		//小球半径
var boxBoundLeft = boxx + ballRadius; //左边界
var boxBoundRight = boxx + boxWidth - ballRadius; //右边界
var boxBoundTop = boxy + ballRadius;		//上边界
var boxBoundBottom = boxy + boxHeight - ballRadius;		//下边界
var ctx; 	//画布上下文
var ballvx = 10;		//球每次移动的x距离
var ballvy = 10;		//球每次移动的Y距离

function init(){
	ctx = document.getElementById('mycanvas').getContext('2d');
	ctx.lineWidth = ballRadius;
	ctx.fillStyle = 'rgb(200,0,50)';
	moveball();
	setInterval(moveball,24);
}


function moveball(){
	ctx.clearRect(boxx,boxy,boxWidth,boxHeight);
	moveandcheck();
	ctx.beginPath();
	ctx.arc(ballx,bally,ballRadius,0,2*Math.PI,true);
	ctx.fill();
	ctx.strokeRect(boxx,boxy,boxWidth,boxHeight);
}

function moveandcheck(){
		//ballvx = .85*ballvx;
		//ballvy = .85*ballvy;
		 var nballx = ballx + ballvx;
		 var nbally = bally + ballvy;
		
	if(nballx<boxBoundLeft){
		ballvx = -.85*ballvx;
		nballx = boxBoundLeft;
	}
	
	if(nballx>boxBoundRight){
		ballvx = -.85*ballvx;
		nballx = boxBoundRight;
	}
	
	if(nbally>boxBoundBottom){
		nbally = boxBoundBottom;
		ballvy = -.85*ballvy;
	}
	
	if(nbally<boxBoundTop){
		ballvy = -.85*ballvy;
		nbally = boxBoundTop;
	}
	
	ballx = nballx;
	bally = nbally ;
}
<body onLoad="init()">
		<canvas id="mycanvas" width="400px" height="400px">
			你的浏览器不支持canvas
		</canvas>
	</body>