程序運行截圖如下:
就是這個球,遇到底端及左右兩邊都可以彈
源碼如下:
canvas4.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="canvas" style="display: block; margin: 50px auto;">
</canvas>
<script src="js/test4.js"></script>
</body>
</html>
test4.js
;
const WIDTH = 1024;
const HEIGHT = 768;
const RADIUS = 15;
let ball = {
x: WIDTH / 2,
y: 30,
g: 1.5 + Math.random(),
vx: Math.pow(-1, Math.ceil(Math.random() * 10)) * 4,
vy: -5,
color: '#CC0000'
};
window.onload = function(){
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
contextBuffer.width = WIDTH;
contextBuffer.height = HEIGHT;
canvas.width = WIDTH;
canvas.height = HEIGHT;
render(context, contextTmp);
setInterval(
function(){
render(context, contextTmp);
update();
},
50
);
}
function update(){
ball.x += ball.vx;
ball.y += ball.vy;
ball.vy += ball.g;
//最頂端不放
if(ball.y > HEIGHT - RADIUS){ //最低端
ball.y = HEIGHT - RADIUS;
ball.vy = -ball.vy * 0.75;
}
if(ball.x < 0 + RADIUS){ //最左端
ball.x = RADIUS;
ball.y = HEIGHT - RADIUS;
ball.vy = -Math.random() * 100 + 30;
ball.vx = Math.random() * 100 + 30;
}
if((WIDTH - RADIUS) - ball.x < 0){ //最右端
ball.x = WIDTH - RADIUS;
ball.y = HEIGHT - RADIUS;
ball.vy = -Math.random() * 100 + 30;
ball.vx = -Math.random() * 100 + 30;
}
}
function render(cxt){
cxt.clearRect(0, 0, WIDTH, HEIGHT);
cxt.fillStyle = ball.color;
cxt.beginPath();
cxt.arc(ball.x, ball.y, 15, 0, 2 * Math.PI);
cxt.closePath();
cxt.fill();;
}
這裏只提示幾個地方,一個是clearRect()可以清空指定位置的畫板。
ball裏面的vx指水平方向的速度,vy指垂直方向的速度,g值加速度。