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

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

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

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

html:

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

css:

* {
padding:;
margin:;
} body {
background-color: #fff;
}

js:

 window.onload = function () {
var CANVAS_HEIGHT=600;
var CANVAS_WIDTH = 1300;
var u = 0.6;//能耗系数
var g = 4;//重力加速度
var timer;
var ball = { x: 100, y: 500, Vx: 5, Vy: 100, r: 5, color: "#4cff00" }; var canvas = document.getElementById("canvas");
canvas.height = CANVAS_HEIGHT;
canvas.width = CANVAS_WIDTH; var ctx = canvas.getContext("2d"); function draw() {
ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);//清除小球在canvas上前一帧的状态
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI);
ctx.fillStyle = ball.color;
ctx.fill();
}
function update() {
ball.x += ball.Vx;
if (ball.Vy==0&&ball.y >= CANVAS_HEIGHT - ball.r) {
ball.Vy = 0;
}
else {
ball.Vy += g;
}
ball.y += ball.Vy;
console.log(ball.Vy);
if (ball.y>CANVAS_HEIGHT - ball.r) {
ball.y = CANVAS_HEIGHT - ball.r;
ball.Vy = -Math.ceil(ball.Vy*u);
}
if (ball.x == 0 + ball.r || ball.x == CANVAS_WIDTH) {
clearInterval(timer);
}
}
timer=setInterval(function () {
draw();
update();
}, 40);
}
上一篇:三种C#.net生成静态页面的方法


下一篇:Bootstrap页面布局16 - BS导航菜单和其响应式布局以及导航中的下拉菜单