paper.js/examples/Scripts/BouncingBalls.html

86 lines
2.5 KiB
HTML
Raw Normal View History

2011-02-21 08:31:26 -05:00
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Example</title>
<link rel="stylesheet" href="../css/style.css">
2011-03-07 20:07:26 -05:00
<script type="text/javascript">var root = '../../'</script>
<script type="text/javascript" src="../../src/load.js"></script>
2011-03-04 06:38:38 -05:00
<script type="text/paperscript" canvas="canvas">
var balls = [];
var group = new Group();
2011-03-04 06:38:38 -05:00
var Ball = Base.extend({
initialize: function(point, vector) {
if (!vector || vector.isZero()) {
this.vector = Point.random() * 5;
} else {
this.vector = vector * 1.5;
}
this.point = point;
this.dampen = 0.4;
this.gravity = 3;
this.bounce = -0.6;
2011-05-08 10:44:19 -04:00
this.radius = 50 * Math.random() + 30;
this.item = new Path.Circle(point, this.radius);
var color = new HSBColor(Math.random() * 360, 1, 1);
var gradient = new Gradient([color, new RGBColor(0, 0, 0)], 'radial');
this.item.fillColor = new GradientColor(gradient, point,
point + this.radius, this.radius * 0.8);
2011-03-04 06:38:38 -05:00
group.appendTop(this.item);
},
2011-03-04 06:38:38 -05:00
iterate: function() {
var size = view.size;
2011-03-04 06:38:38 -05:00
this.vector.y += this.gravity;
this.vector.x *= 0.99;
var pre = this.point + this.vector;
if (pre.x < this.radius || pre.x > size.width - this.radius)
this.vector.x *= -this.dampen;
if (pre.y < this.radius || pre.y > size.height - this.radius) {
if (Math.abs(this.vector.x) < 3)
this.vector = Point.random() * [150, 100] + [-75, 20];
2011-03-04 06:38:38 -05:00
this.vector.y *= this.bounce;
}
var max = Point.max(this.radius, this.point + this.vector);
this.item.position = this.point = Point.min(max, size - this.radius);
2011-05-08 10:44:19 -04:00
this.item.rotate(this.vector.x / 2);
2011-03-04 06:38:38 -05:00
}
});
2011-03-04 06:38:38 -05:00
for (var i = 0; i < 10; i++) {
var position = Point.random() * view.size;
var vector = (Point.random() - [0.5, 0]) * [50, 100];
var ball = new Ball(position, vector);
2011-03-04 06:38:38 -05:00
balls.push(ball);
}
var lastDelta;
function onMouseDrag(event) {
lastDelta = event.delta;
}
function onMouseUp(event) {
var ball = new Ball(event.point, lastDelta);
balls.push(ball);
lastDelta = null;
}
2011-03-04 06:38:38 -05:00
var boundPath = new Path.Rectangle([-10, -10], [-11, -11]);
boundPath.style = {
strokeColor: 'red',
strokeWidth: 1
};
function onFrame() {
for (var i = 0, l = balls.length; i < l; i++)
2011-03-04 06:38:38 -05:00
balls[i].iterate();
boundPath.bounds = group.bounds;
}
</script>
</head>
<body>
<p>Click to add circles:</p>
<canvas id="canvas" resize stats keepalive="true"></canvas>
</body>