var canvas;
var ctx;
var world;
var sw;
var sh;
var fixedTimeStep = 1 / 60;
var colorList = [
'#f64c4c',
'#f6844c',
'#d0f64c',
'#4cc8f6'
]
function main() {
canvas = document.getElementById('stage');
canvas.style.backgroundColor = '#ffffff';
ctx = canvas.getContext('2d');
world = new p2.World({
gravity: [0, -9.82]
});
window.addEventListener('resize', resize);
resize();
var wallThickness = 10;
//左
createWall(0, sh/2, wallThickness, sh);
//右
createWall(sw, sh/2, wallThickness, sh);
//下
createWall(sw/2, sh, sw, wallThickness);
requestAnimationFrame(animate);
}
function animate(time) {
requestAnimationFrame(animate);
world.step(fixedTimeStep);
render();
}
function render() {
ctx.clearRect(0, 0, sw, sh);
createBall();
for (var i = world.bodies.length - 1; i >= 0; i--) {
var body = world.bodies[i];
var shape = body.shapes[0];
if (shape.type == p2.Shape.CIRCLE) {
var bodyY = body.position[1] * -100;
if(bodyY > sh+50) {
world.removeBody(body);
} else {
drawCircle(body, shape);
}
} else if (shape.type == p2.Shape.BOX) {
drawBox(body, shape);
}
}
}
function createBall() {
var randX = Math.random() * 50 - 25;
var randY = Math.random() * 50 - 25;
var xx = (sw / 2 + randX) / 100;
var yy = (randY) / -100;
var radius = 20 / 100;
var ballShape = new p2.Circle({radius:radius});
var ballBody = new p2.Body({
mass:1.0,
position: [xx, yy]
});
var colorID = Math.floor(Math.random() * colorList.length);
var color = colorList[colorID];
ballBody.color = color;
ballBody.addShape(ballShape);
world.addBody(ballBody);
}
function createWall(x, y, w, h) {
var xx = (x) / 100;
var yy = -(y) / 100;
var wid = w / 100;
var hei = h / 100;
var shape = new p2.Box({width:wid, height:hei});
body = new p2.Body({
mass:0,
position:[xx, yy]
});
body.addShape(shape);
world.addBody(body);
}
function resize(evt) {
sw = window.innerWidth;
sh = window.innerHeight;
canvas.width = sw;
canvas.height = sh;
}
function drawCircle(body, shape) {
var x = body.position[0];
var y = body.position[1];
var xx = x * 100;
var yy = -y * 100;
var radius = shape.radius;
var radius2 = radius * 100;
ctx.beginPath();
ctx.fillStyle = body.color || 'rgba(240, 0, 0, 1.0)';
ctx.arc(xx, yy, radius2, 0, 2*Math.PI);
ctx.fill();
}
function drawBox(body, shape) {
ctx.fillStyle = "rgb(200,0,0)";
ctx.lineWidth = 2;
ctx.strokeStyle = '#666666';
ctx.beginPath();
var x = body.position[0];
var y = body.position[1];
var xx = x * 100;
var yy = -y * 100;
var shapeX = -shape.width * 100 / 2;
var shapeY = -shape.height * 100 / 2;
var shapeW = shape.width * 100;
var shapeH = shape.height * 100;
ctx.save();
ctx.translate(xx, yy);
ctx.rotate(body.angle);
ctx.rect(shapeX, shapeY, shapeW, shapeH);
ctx.fill();
ctx.restore();
}
main();
<canvas id="stage"></canvas>
html, body {
margin: 0;
padding: 0;
width:100%;
height:100%;
overflow: hidden;
}
External resources loaded into this fiddle: