canvas 模拟小球上抛运动的物理效果

最近一直想用学的canvas做一个漂亮的小应用,但是,发现事情并不是想的那么简单。比如,游戏的逼真效果,需要自己来coding……

所以,自己又先做了一个小demo,算是体验一下亲手打造物理引擎的感觉吧。*_*

代码效果预览地址:http://code.w3ctech.com/detail/2524

html:

1 <div class="container">
2     <canvas id="canvas" style="border:1px solid #ccc; opacity:0.7"></canvas>
3 </div>

css:

* {
            padding: 0;
            margin: 0;
        }

        body {
            background-color: #fff;
        }

js:

 1 window.onload = function () {
 2             var CANVAS_HEIGHT=600;
 3             var CANVAS_WIDTH = 1300;
 4             var u = 0.6;//能耗系数
 5             var g = 4;//重力加速度
 6             var timer;
 7             var ball = { x: 100, y: 500, Vx: 5, Vy: 100, r: 5, color: "#4cff00" };
 8 
 9             var canvas = document.getElementById("canvas");
10             canvas.height = CANVAS_HEIGHT;
11             canvas.width = CANVAS_WIDTH;
14 
15             var ctx = canvas.getContext("2d");
16 
17             function draw() {
18                 ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);//清除小球在canvas上前一帧的状态
19                 ctx.beginPath();
20                 ctx.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI);
21                 ctx.fillStyle = ball.color;
22                 ctx.fill();
23             }
24             function update() {
25                 ball.x += ball.Vx;
26                 if (ball.Vy==0&&ball.y >= CANVAS_HEIGHT - ball.r) {
27                     ball.Vy = 0;
28                 }
29                 else {
30                     ball.Vy += g;
31                 }
32                 ball.y += ball.Vy;
33                 console.log(ball.Vy);
34                 if (ball.y>CANVAS_HEIGHT - ball.r) {
35                     ball.y = CANVAS_HEIGHT - ball.r;
36                     ball.Vy = -Math.ceil(ball.Vy*u);
37                 }
38                 if (ball.x == 0 + ball.r || ball.x == CANVAS_WIDTH) {
39                     clearInterval(timer);
40                 }
41             }
42             timer=setInterval(function () {
43                 draw();
44                 update();
45             }, 40);
46         }

 

posted @ 2016-02-14 22:44  我一路向北  阅读(691)  评论(0编辑  收藏  举报