Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <span>PERFECTLY TRACKING A CUBIC-BEZIER CURVE VIA JAVASCRIPT - <a href="https://twitter.com/1dayitwillmake">@1dayitwillmake</a></span>
<div class="animatedBox" id="webkitTransitionDiv"></div>
<div class="animatedBox" id="tracker"></div>
<div class="animatedBox" id="tracker2"></div>
              
            
!

CSS

              
                body {
  background-color: #DDD9D6;
  font-family: helvetica;
}
#sliders {
  position: absolute;
  top: 80px;
}
span {
  font-family: helvetica;
  font-weight: bold;
}
a, a:visited {
  text-decoration:none;
  outline:none;
  color:#54a6de;
}
.animatedBox {
  will-change: transform;
  top:30px;
  border-radius:4px;
  font-family: helvetica; font-weight: bold; 
  margin: 10px auto;
  position:absolute;
  left: 0px; 
  padding-left:5px;
  font-size: 20px; 
  width: 250px; 
  background-color: rgba(93, 228, 240, 0.45);
}
              
            
!

JS

              
                
var tracker, tracker2, webkitTranstionDiv;
var animationStartTime, animationDuration;
var startPosition, endPosition;
var cubicCurve;
var animateTimeout;
var keepAnimating = false


init();
function init() {
  keepAnimating = true
  
	// Change curve properties to see effect
	cubicCurve = {"A": .49, "B": 0, "C": 0.51, "D":1}; 
	animationDuration = 9.1;
 	endPosition = new Point(450, 100);


	// Create the div that will be animated by webkit
	webkitTranstionDiv = document.querySelector("#webkitTransitionDiv");
  console.log(webkitTranstionDiv)
	// Actual interesting part of the css
	webkitTranstionDiv.style.cssText += 'transition-property: transform, all;transition-timing-function: cubic-bezier('+cubicCurve.A+","+cubicCurve.B+","+cubicCurve.C+","+cubicCurve.D+')';
	webkitTranstionDiv.style.webkitTransitionDuration = animationDuration+'s';
	webkitTranstionDiv.innerHTML = 'cubic-bezier<br>('+cubicCurve.A+","+cubicCurve.B+","+cubicCurve.C+","+cubicCurve.D+')';


 
  
  	// Div that will track the CSS3 animated one
	tracker = document.querySelector("#tracker");
  console.log("Tracker:", tracker);
  tracker.yPadding = 85;
	tracker.style.cssText += "top: "+tracker.yPadding+"px;";
	tracker.innerHTML = 'trackingDiv';

	tracker2 = document.querySelector("#tracker2");
  console.log("Tracker:", tracker2);
  tracker2.yPadding = 115;
	tracker2.style.cssText += "top: "+tracker2.yPadding+"px;";
	tracker2.innerHTML = 'trackingDiv';
  
	// Start the webkit animation on a timeout just to make sure our maths are correct
	requestAnimationFrame(function(){
		startPosition = new Point(0, 0); // Or use - aCSSTransform.match(/-?\d+\.*\d*px/g).map(function(N) {return parseFloat(N)});
		animationStartTime = Date.now();

		// Start the webkit animation
		webkitTranstionDiv.style.transform ='translate3d('+endPosition.x+'px, '+endPosition.y+'px, 0px)';
		webkitTranstionDiv.style.backgroundColor = "rgba(255, 84, 228, 0.69)"
		// Start our loop
		animate();
	});

  	// Stop timer once our timer is done
	webkitTranstionDiv.addEventListener('webkitTransitionEnd', function(){
    keepAnimating = false
		clearTimeout( animateTimeout );
	}, false);
}


// Main loop - solves T along the cubic curve
function animate() {
	var now = Date.now();
	var t = (now - animationStartTime) / ( animationDuration*1000 );

	var curve = new UnitBezier(cubicCurve.A, cubicCurve.B, cubicCurve.C, cubicCurve.D);
	var t1 = curve.solve(t, UnitBezier.prototype.epsilon);
	var s1 = 1.0-t1;

	// Lerp using solved T
    var offsetX = (startPosition.x * s1) + (endPosition.x * t1);
    var offsetY = (startPosition.y * s1) + (endPosition.y * t1);
	
    // Update info
	tracker.innerHTML = "Unit Solved t="+Math.round(t1*1000)/1000;//PT.toString();
	tracker.style.left = offsetX+"px";
	tracker.style.top = (tracker.yPadding+offsetY)+"px";
	
  // Second method
  t1=cubicBezier(cubicCurve.A, cubicCurve.B, cubicCurve.C, cubicCurve.D, t);
  s1 = 1.0-t1;;
  offsetX = (startPosition.x * s1) + (endPosition.x * t1);
  offsetY = (startPosition.y * s1) + (endPosition.y * t1);
  
 	tracker2.innerHTML = "Cubic Solved t="+Math.round(t1*1000)/1000;//PT.toString();
	tracker2.style.left = offsetX+"px";
	tracker2.style.top = (tracker2.yPadding+offsetY)+"px";

  if(!keepAnimating){
    return
  }
  
	// Reset timeout
  requestAnimationFrame(animate)
}	

/**
* Solver for cubic bezier curve with implicit control points at (0,0) and (1.0, 1.0)
*/
function UnitBezier(p1x, p1y, p2x, p2y) {
	// pre-calculate the polynomial coefficients
	// First and last control points are implied to be (0,0) and (1.0, 1.0)
	this.cx = 3.0 * p1x;
	this.bx = 3.0 * (p2x - p1x) - this.cx;
	this.ax = 1.0 - this.cx -this.bx;
	 
	this.cy = 3.0 * p1y;
	this.by = 3.0 * (p2y - p1y) - this.cy;
	this.ay = 1.0 - this.cy - this.by;
}

UnitBezier.prototype.epsilon = 1e-5;; // Precision  
UnitBezier.prototype.sampleCurveX = function(t) {
    return ((this.ax * t + this.bx) * t + this.cx) * t;
}
UnitBezier.prototype.sampleCurveY = function (t) {
    return ((this.ay * t + this.by) * t + this.cy) * t;
}
UnitBezier.prototype.sampleCurveDerivativeX = function (t) {
    return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
}
UnitBezier.prototype.solveCurveX = function (x, epsilon) {
	var t0;	
	var t1;
	var t2;
	var x2;
	var d2;
	var i;

	// First try a few iterations of Newton's method -- normally very fast.
	for (t2 = x, i = 0; i < 32; i++) {
	    x2 = this.sampleCurveX(t2) - x;
	    if (Math.abs (x2) < epsilon)
	        return t2;
	    d2 = this.sampleCurveDerivativeX(t2);
	    if (Math.abs(d2) < epsilon)
	        break;
	    t2 = t2 - x2 / d2;
	}

	// No solution found - use bi-section
	t0 = 0.0;
	t1 = 1.0;
	t2 = x;

	if (t2 < t0) return t0;
	if (t2 > t1) return t1;

	while (t0 < t1) {
		x2 = this.sampleCurveX(t2);
		if (Math.abs(x2 - x) < epsilon)
			return t2;
		if (x > x2) t0 = t2;
		else t1 = t2;

		t2 = (t1 - t0) * .5 + t0;
	}

	// Give up
	return t2;
}

// Find new T as a function of Y along curve X
UnitBezier.prototype.solve = function (x, epsilon) {
    return this.sampleCurveY( this.solveCurveX(x, epsilon) );
}
  
  // Simple value Point object 
function Point(p1x, p1y) { this.x = p1x; this.y = p1y; };

// Alternate method found in Ocanvas
function cubicBezier(x1, y1, x2, y2, time) {

  // Inspired by Don Lancaster's two articles
  // http://www.tinaja.com/glib/cubemath.pdf
  // http://www.tinaja.com/text/bezmath.html

  // Set start and end point
  var x0 = 0,
    y0 = 0,
    x3 = 1,
    y3 = 1,

    // Convert the coordinates to equation space
    A = x3 - 3*x2 + 3*x1 - x0,
    B = 3*x2 - 6*x1 + 3*x0,
    C = 3*x1 - 3*x0,
    D = x0,
    E = y3 - 3*y2 + 3*y1 - y0,
    F = 3*y2 - 6*y1 + 3*y0,
    G = 3*y1 - 3*y0,
    H = y0,

    // Variables for the loop below
    t = time,
    iterations = 5,
    i, slope, x, y;

  // Loop through a few times to get a more accurate time value, according to the Newton-Raphson method
  // http://en.wikipedia.org/wiki/Newton's_method
  for (i = 0; i < iterations; i++) {

    // The curve's x equation for the current time value
    x = A* t*t*t + B*t*t + C*t + D;

    // The slope we want is the inverse of the derivate of x
    slope = 1 / (3*A*t*t + 2*B*t + C);

    // Get the next estimated time value, which will be more accurate than the one before
    t -= (x - time) * slope;
    t = t > 1 ? 1 : (t < 0 ? 0 : t);
  }

  // Find the y value through the curve's y equation, with the now more accurate time value
  y = Math.abs(E*t*t*t + F*t*t + G*t * H);

  return y;
}
              
            
!
999px

Console