效果
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>engineer</title>
<style type = "text/css">
div{
margin-top:30px;
text-align: center;
}
</style>
</head>
<body>
<div>
<h1>小球弹跳游戏</h1>
<input type="button" id = "btnBegin" value = "开始游戏" /><br/>
<canvas id = "cv" height = "600px" width = "600px">
</canvas>
</div>
<script src = "my3.js"></script>
</body>
</html>
js
var canvas = document.getElementById("cv");
var ctx = canvas.getContext('2d');
var btnBegin = document.getElementById("btnBegin");
var width = ctx.canvas.width;
var height = ctx.canvas.height;
var ballX = parseInt(Math.random()*canvas.width);
var ballY = parseInt(Math.random()*canvas.height);
var AddX = -5;
var AddY = -5;
btnBegin.onclick = function (){
document.getElementById("cv").onmouseup = canvas_mouseup;
draw();
document.getElementById("btnBegin").disabled = "disabled";
setInterval(draw,200);
}
function draw(){
ctx.clearRect(0,0,width,height);
ctx.save();
ctx.fillStyle = "lightgreen";
ctx.strokeStyle = "black";
ctx.linewidth = 3;
ctx.fillRect(3,3,width-5,height-5);
ctx.strokeRect(3,3,width-5,height-5);
ctx.beginPath();
ctx.fillStyle = "blue";
ctx.arc(ballX,ballY,5,0,2*Math.PI,false);
ballX+=AddX;
ballY+=AddY;
if (ballX<5) {
ballX=5;
AddX = -AddX;
}else if (ballX > width-5) {
ballX = width-5;
AddX = - AddX;
}
if (ballY<5) {
ballY=5;
AddY = -AddY;
}else if (ballY > height-5) {
ballY = height-5;
AddY = - AddY;
}
ctx.closePath();
ctx.fill();
ctx.restore();
}
function canvas_mouseup(ev)
{
var dX;
var dY;
dX = ev.pageX - document.getElementById('cv').offsetLeft -ballX;
dY = ev.pageY - document.getElementById('cv').offsetTop -ballY;
if (-5<=dX&&dX<=5&&-5<=dY&&dY<=5) {
alert("恭喜您获胜!游戏结束!");
document.getElementById("btnBegin").disabled = "";
}
}