HTML5 打地鼠简化版
1、canvas 画图的时候相对的坐标是画板‘
2、浏览器兼容性问题,在IE下面是clientX clientY
3、修改小球的运动轨迹可以在addX和addY上面下功夫 ~
4、修改容人值可以修改 catch_ball函数 代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript"> var ballX,ballY; var addX,addY; var intervalId ; var context ; var canvas ; var whdth; var height = 500; function catch_ball(ev){ alert('catch'); var x = ev.pageX; var y = ev.pageY; // get position relative to canvas . var relativeX = x - document.getElementById("mycanvas").offsetLeft; var relativeY = y - document.getElementById("mycanvas").offsetTop; //judge whether clicked the ball if(-5<(relativeX - ballX)&&(relativeX - ballX)<=5){ if(-5<(relativeY - ballY)&&(relativeY - ballY)<=5){ alert('congratulation to you ~~~ ,you are win .'); clearInterval(intervalId); document.getElementById("start_btn").disabled = ""; } } } function windowLoad(){ document.getElementById("mycanvas").onclick = catch_ball; } function jump(){ context.clearRect(0,0,width,height); context.save(); //draw ball table . context.fillStyle = "lightgreen"; context.strokeStyle = "black"; context.lineWidth = 3; context.fillRect(3,3,width -6,height-6); context.strokeRect(3,3,width-6,height-6); //draw ball . context.beginPath(); context.fillStyle = "blue"; context.arc(ballX,ballY,5,0,2*Math.PI,false); ballX += addX; ballY += addY; //alert(ballX+":"+ballY); //modify position . if(ballX<5){ ballX = 5; addX = -addX; } if(ballY <5){ ballY = 5; addY = -addY; } if(ballX>width-6){ ballX = width-6; addX = -addX; } if(ballY>height-6){ ballY = height-6; addY = -addY; } context.closePath(); context.fill(); context.restore(); } function startclick(){ // alert('game start '); canvas = document.getElementById("mycanvas"); context = canvas.getContext("2d"); width = canvas.width; height = canvas.height; //alert(height); //init ball init position . ballX = parseInt(Math.random()*width); ballY = parseInt(Math.random()*height); addX = -5; addY = -5; jump(); //test //context.fillStyle = "red"; //context.fillRect(5,5,20,20); intervalId = setInterval("jump()",200); document.getElementById("start_btn").disabled = "disabled"; } </script> </head> <body onload="windowLoad();"> <h1> jump game </h1> <H2>click the start button , then click jumping ball .</H2> <input type="button" value="start game" id="start_btn" onclick="startclick();"/> <div style="width:600px;height:550px;border:blue solid 2px;"> <canvas id="mycanvas" width="500px" height="500px"> broswer is not support !</canvas> </div> </body> </html>