<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8"/>
<title>
HTML实现弹跳球
</title>
</head>
<body>
<canvas id="mc" width="380" height="320" style="border:1px solid black"></canvas>
<script type/javascript>
CanvasRenderingContext2D.prototype.fillCircle =
function(x, y, radius, pattern)
{
ctx.save();
ctx.translate(x,y);
ctx.beginPath();
ctx.arc(0, 0, radius, 0, Math.PI2, true);
ctx.fillStyle = pattern;
ctx.closePath();
ctx.fill();
ctx.restore();
}
var canvas = document.getElementById("mc");
var ctx = canvas.getContext('2d');
var radius = 15;
var rg = ctx.createRadialGradient(0, 0 , radius/2,
0 , 0, radius);
rg.addColorStop(0.0, "#000");
rg.addColorStop(1.0, "#fff");
var x = canvas.width/2;
var y = 20;
var xSpeed = Math.random()11-5;
var ySpeed = Math.random()*5+2;
function draw()
{
ctx.fillStyle="#000";
ctx.clearRect(x-radius-2, y-radius-2,
x+xSpeed+radius+2, y+ySpeed+radius+2);
x+=xSpeed;
y+=ySpeed;
ctx.fillCircle(x, y, 15, rg);
if(x <= radius || x>= canvas.width-radius)
{
xSpeed=-xSpeed;
}else if( y<=radius ||y>canvas.height-radius)
{
ySpeed=-ySpeed;
}
}
setInterval(draw, 200);
</script>
</body>
</html>
网友评论