效果如图:
html:
Title
ball.js:
var ball = {x:512,y:100,r:20,g:2,vx:10,vy:0,color:"#058"}; window.onload = function () { var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); canvas.width = 1024; canvas.height = 768; setInterval( function () { update(); render(context); },50) }; function update() { ball.x+=ball.vx; ball.y+=ball.vy; ball.vy+=ball.g; } function render(cxt) { cxt.clearRect(0,0,cxt.canvas.width,cxt.canvas.height); cxt.fillStyle = ball.color; cxt.beginPath(); cxt.arc(ball.x,ball.y,ball.r,0,2*Math.PI); cxt.closePath(); cxt.fill(); }
小球反弹了:
ball.js:
//更新
function update() {
ball.x+=ball.vx;
ball.y+=ball.vy;
ball.vy+=ball.g;
ball.vy = -ball.vy;
}else if(ball.x>=canvas.width-ball.r){
ball.vx = -ball.vx;
}else if(ball.x<=ball.r) {
ball.vx = -ball.vx;
}else if(ball.y<=ball.r){
ball.vy = -ball.vy;
}
}