paper.js/examples/Paperjs.org/BouncingBalls.html

104 lines
3.3 KiB
HTML
Raw Normal View History

2011-02-21 08:31:26 -05:00
<!DOCTYPE html>
<html>
<head>
2014-08-16 13:24:54 -04:00
<meta charset="UTF-8">
<title>Bouncing Balls</title>
<link rel="stylesheet" href="../css/style.css">
<script type="text/javascript" src="../../dist/paper-full.js"></script>
<script type="text/paperscript" canvas="canvas">
var Ball = function(point, vector) {
if (!vector || vector.isZero()) {
this.vector = Point.random() * 5;
} else {
this.vector = vector * 2;
}
this.point = point;
this.dampen = 0.4;
this.gravity = 3;
this.bounce = -0.6;
2014-08-16 13:24:54 -04:00
var color = {
hue: Math.random() * 360,
saturation: 1,
brightness: 1
};
var gradient = new Gradient([color, 'black'], true);
2014-08-16 13:24:54 -04:00
var radius = this.radius = 50 * Math.random() + 30;
// Wrap CompoundPath in a Group, since CompoundPaths directly
// applies the transformations to the content, just like Path.
var ball = new CompoundPath({
children: [
new Path.Circle({
radius: radius
}),
new Path.Circle({
center: radius / 8,
radius: radius / 3
})
],
fillColor: new Color(gradient, 0, radius, radius / 8),
});
2014-08-16 13:24:54 -04:00
this.item = new Group({
children: [ball],
applyMatrix: false,
position: this.point
});
}
2014-08-16 13:24:54 -04:00
Ball.prototype.iterate = function() {
var size = view.size;
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];
this.vector.y *= this.bounce;
}
2014-08-16 13:24:54 -04:00
var max = Point.max(this.radius, this.point + this.vector);
this.item.position = this.point = Point.min(max, size - this.radius);
this.item.rotate(this.vector.x);
};
2014-08-16 13:24:54 -04:00
var balls = [];
for (var i = 0; i < 10; i++) {
var position = Point.random() * view.size,
vector = (Point.random() - [0.5, 0]) * [50, 100],
ball = new Ball(position, vector);
balls.push(ball);
}
2011-03-04 06:38:38 -05:00
2014-08-16 13:24:54 -04:00
var textItem = new PointText({
point: [20, 30],
fillColor: 'black',
content: 'Click, drag and release to add balls.'
});
2014-08-16 13:24:54 -04:00
var lastDelta;
function onMouseDrag(event) {
lastDelta = event.delta;
}
2014-08-16 13:24:54 -04:00
function onMouseUp(event) {
var ball = new Ball(event.point, lastDelta);
balls.push(ball);
lastDelta = null;
}
2014-08-16 13:24:54 -04:00
function onFrame() {
for (var i = 0, l = balls.length; i < l; i++)
balls[i].iterate();
}
</script>
</head>
<body>
2014-08-16 13:24:54 -04:00
<canvas id="canvas" resize></canvas>
2011-05-30 18:27:39 -04:00
</body>
</html>