- <!doctype html5>
- <html>
- <head>
- <meta charset=gbk>
- <style>
- canvas{border:1px solid red;}
- </style>
- </head>
- <body>
- <canvas id="mycanvas" width=900px height=600px></canvas>
- <form>
- 初始垂直速度:<input id="verSpeed" type="number" value=20 />(px/s)
- 初始水平速度:<input id="horSpeed" type="number" value=50 />(px/s)
- <input value="开始" id="begin" type="button" />
- </form>
- <script>
- var mycanvas = $("mycanvas");
- var ctx = mycanvas.getContext("2d");
- var begin = $("begin");
- var frame = 100;
- var iniX = 80; //初始横坐标
- var iniY = 290; //小球初始纵坐标
- var rad1 = 10; //小球半径
- var g = 10; //垂直加速度g
- var vX; //初始的水平速度
- var vY; //初始的垂直速度
- initial(ctx); //界面初始化
- var cball = new Ball(iniX,iniY,rad1);
- cball.draw(ctx);
- //cball.move();
- //var stopSign = setInterval(cball.move,1000/frame);
- begin.onclick = function beginMove(){
- ctx.clearRect(3,3,897,597);
- initial(ctx);
- cball.init();
- stopSign = setInterval(cball.move,1000/frame);
- }
- function initial(o){
- o.beginPath();
- o.lineWidth = 3;
- o.moveTo(20,20);
- o.lineTo(800,20);
- o.moveTo(20,20);
- o.lineTo(20,500);
- o.moveTo(800,10);
- o.lineTo(810,20);
- o.lineTo(800,30);
- o.moveTo(10,500);
- o.lineTo(20,510);
- o.lineTo(30,500);
- o.stroke();
- o.fillStyle = "#478d8d";
- o.fillRect(50,300,700,40);
- o.fillStyle = "#ff0f0f";
- o.fillRect(500,50,20,250);
- }
- function Ball(bx,by,rad){
- this.bx = bx;
- this.by = by;
- this.rad = rad;
- this.init = ballInit;
- this.move = horizontalThrow;
- this.draw = drawBall;
- }
- function ballInit(){
- cball.bx = iniX;
- cball.by = iniY;
- vX = Number($("horSpeed").value);
- vY = Number($("verSpeed").value);
- }
- function horizontalThrow(){
- ctx.clearRect(cball.bx-cball.rad-1,cball.by-cball.rad-2,cball.rad*2+1,cball.rad*2+2);
- cball.bx += vX/frame;
- cball.by -= vY/frame;
- vY -= 10/frame;
- cball.draw(ctx);
- checkTouch();
- }
- function checkTouch(){
- if(cball.bx+cball.rad > 500){
- clearInterval(stopSign);
- }else if(cball.by+cball.rad > 300){
- clearInterval(stopSign);
- }
- }
- function drawBall(o){
- o.beginPath();
- o.fillStyle = "#ff870f";
- o.arc(this.bx,this.by-1,this.rad,0,2*Math.PI,true);
- o.fill();
- }
- function $(id){
- return document.getElementById(id);
- }
- </script>
- </body>
- </html>
- //该片段来自于http://www.codesnippet.cn/detail/210820135276.html
来源: http://www.codesnippet.cn/detail/210820135276.html