tween.js/examples/05_spline.html
2012-04-03 04:09:50 +02:00

123 lines
2.9 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<title>Tween.js / Spline</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
body {
margin: 0px;
}
#target {
font-size: 13px;
padding: 0px 32px;
}
</style>
<link href="css/style.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="info" style="position: relative;">
<h1><a href="http://github.com/sole/tween.js">tween.js</a></h1>
<h2>05 _ Spline</h2>
<p>Catmull-Rom. It's all you need.</p>
</div>
<div id="target"></div>
<script src="../src/Tween.js"></script>
<script>
init();
TWEEN.start();
function init() {
var target = document.getElementById('target');
var canvas = document.createElement( 'canvas' );
canvas.width = 1024;
canvas.height = 512;
target.appendChild( canvas );
var context = canvas.getContext( '2d' );
context.fillStyle = "rgb(250,250,250)";
context.fillRect( 0, 0, 1024, 512 );
context.lineWidth = 2;
context.strokeStyle = "rgb(255,127,127)";
context.fillStyle = "rgba(0,0,0,0.3)";
var points = [];
for ( var i = 0; i < 20; i ++ ) {
points[ i ] = { x: Math.random() * 1024, y: Math.random() * 512 };
context.fillRect( points[ i ].x - 2, points[ i ].y - 2, 4, 4 );
}
var dummy = { p: 0 };
var position = { x: 0, y: 0 };
var position_old = { x: points[ 0 ].x, y: points[ 0 ].y };
var spline = new Spline();
new TWEEN.Tween( dummy ).to( { p: 1 }, 20000 ).easing( TWEEN.Easing.Linear.EaseNone ).onUpdate( function() {
position = spline.get2DPoint( points, this.p );
context.beginPath();
context.moveTo( position_old.x, position_old.y );
context.lineTo( position.x, position.y );
context.closePath();
context.stroke();
position_old.x = position.x;
position_old.y = position.y;
}).start();
}
function Spline() {
var c = [], v2 = { x: 0, y: 0 },
point, intPoint, weight;
this.get2DPoint = function ( points, k ) {
point = ( points.length - 1 ) * k;
intPoint = Math.floor( point );
weight = point - intPoint;
c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
c[ 1 ] = intPoint;
c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
v2.x = interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
v2.y = interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
return v2;
}
// Catmull-Rom
function interpolate( p0, p1, p2, p3, t ) {
var v0 = ( p2 - p0 ) * 0.5;
var v1 = ( p3 - p1 ) * 0.5;
var t2 = t * t;
var t3 = t * t2;
return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
}
}
</script>
</body>
</html>