Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ 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

Auto Save

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

              
                <canvas></canvas>
<canvas></canvas>
<canvas></canvas>
<svg viewBox="0 0 10 10" version="1.1"
     xmlns="http://www.w3.org/2000/svg"
     id="dSprite">
  <circle cx="5" cy="5" r="5" style="fill: #db1313"/>
</svg>
<svg viewBox="0 0 10 10" version="1.1"
     xmlns="http://www.w3.org/2000/svg">
  <circle cx="5" cy="5" r="5" style="fill: #1313db"/>
</svg>
<div id="parameter"><i>t</i> = <span>0</span></div>

    <nav>
      <label for="number">Control points: </label>
      <input name="number" id="number" type="number" value="4" min="2" max="14" step="1"><br>
      <button>Clear curves</button>
    </nav>
              
            
!

CSS

              
                @import url(https://fonts.googleapis.com/css?family=Open+Sans:400);

html, body {
	height: 100%;
}

body {
	background: #111;
	color: white;
	margin:0;
}

canvas {
	width: 100%;
	height: 100%;
	position: absolute;
	left:0;
}

svg {
	position: absolute;
}
svg circle {
	opacity:0.8;
}

#parameter, .weight {
	position: absolute;
	font-size: 26px;
	color: white;
}

.weight {
	background: #909;
	padding: 5px;
	font-size: 13px;
	border-radius: 50%/25%;
}

figure#icon {
	position: fixed;

	opacity: .8;
	width: 70px;
	height: 70px;
	background: url("../images/icon.svg") no-repeat;
	background-size: contain;
	margin: 40px;
}

.draghelper {
	position: absolute;
}

nav {
	position: absolute;
	bottom: 20px;
	margin-left: 20px;
}
nav #number {
	font-size: 24px;
}
nav, input, button {
	font: 400 normal 100%/1.3 "Open Sans", sans-serif;
}
nav input {
	font-size: 80%;
	width:50px;
	margin-left: 10px;
}
nav button {
	margin-top: 2em;

}
              
            
!

JS

              
                // potatoDie 2015

var ctx = [],
		bezier,
		slider,
		order = 3;

window.onload = function () {
	bezier = Bezier();
	slider = Slider();

	init();

	// Trouble with resizing the Draggable
	// You ought to look into that
	addEventListener('resize', init, false);

	var n = document.getElementById('number');
	var h = function () {
		order = n.value - 1;
  	var w = window.innerWidth,
				h = window.innerHeight;

		bezier.init(w, h);
		fadeCanvas(ctx[0], 0.5);

		slider.draw(ctx[2]);
	};
	n.addEventListener('change', h );
	n.addEventListener('input', h );

	document.querySelector('button').addEventListener('click', function(){fadeCanvas(ctx[0], 0.5);})
};

function init () {
  var w = window.innerWidth,
			h = window.innerHeight;

	// Plural canvases
	// [1] is for the control points (so you can clear the canvas when dragging them
	// without interfering with the rest)
	// I'll have another canvas for the curve, so you can fade it a little when
	// you start a new one (after dragging a control point) (Not used)
	// [0] is for curve
	// [2] for chrome (slider)
	var canvases = document.getElementsByTagName('canvas');
	for (var i = 0; i < canvases.length; i++) {
		canvases[i].width = w;
		canvases[i].height = h;
		ctx[i] = canvases[i].getContext('2d');
		ctx[i].fillStyle = "#111";
	};
	ctx[1].strokeStyle = "#b98059";
	ctx[2].strokeStyle = "#fff";
	ctx[0].strokeStyle = "#fff";

	bezier.init(w, h);
	slider.init(ctx[2], bezier.update);
}

var Bezier = function () {
	var coordinateSprite, t, point_on_curve;
	var radius = 20;

	// each control point has a weight associated, and a basis function that detrmines the weight
	var cPoints = [];
	var basisF;
	var w = [];	
	
	var explicitFormula = function(t) {
		// Explicit Bezier formula for this curve
		
		var x = 0, y =0;
		
		for (var i = 0; i < cPoints.length; i++) {
			x += w[i] * cPoints[i].x;
			y += w[i] * cPoints[i].y;
		};

		return {x: x, y: y};
	}; 
	

	var init = function (w, h) {
		basisF = createBasis(order);

		// Create order + 1 more or less random control points
		var x, y, el, draghelper,
				offsetWeightSprite = {x: -15, y: 30};
		
		// Clean up DOM and old points, e.g when resizing, or picking a new order
		for (var i = 0; i < cPoints.length; i++) {
			document.body.removeChild(cPoints[i].weightSprite);
			document.body.removeChild(cPoints[i].dragsprite);
		}
		cPoints = [];

		for (var i = 0; i < order + 1; i++) {
			x = rand(200, w-2*radius);
			y = rand(radius, h * 3/5);

			// Create DOM sprite for parameter display
			el = document.createElement('div');
			
			el.className = "weight";
			el.style.left = x - offsetWeightSprite.x + "px";
			el.style.top = y + offsetWeightSprite.y + "px";
			
			document.body.appendChild(el);

			// And another DOM element for helping drag
			draghelper = document.createElement('div');
			draghelper.className = "draghelper";
			draghelper.style.left = x - radius + "px";
			draghelper.style.top = y -radius + "px";
			draghelper.style.width = 2*radius + "px";
			draghelper.style.height = 2*radius + "px";
			document.body.appendChild(draghelper);
			
			cPoints.push({x: x, y: y, weightSprite: el, dragsprite: draghelper});

			Draggable.create(draghelper,
				{	type: 'top,left', 
					onDrag: function(index, e) {
						// You might use e.target instead of cPoints[index].dragsprite

						// Update the corresponding control point
						cPoints[index].x = parseInt(cPoints[index].dragsprite.style.left, 10) + radius;
						cPoints[index].y = parseInt(cPoints[index].dragsprite.style.top, 10) + radius;
						
						// Update the weight display
						cPoints[index].weightSprite.style.left = cPoints[index].x - offsetWeightSprite.x + "px";
						cPoints[index].weightSprite.style.top = cPoints[index].y + offsetWeightSprite.y + "px";
						
						drawControlPoints();

						// You want to update the current Bezier coordinate too (its sprite).
						update(t);
					}.bind(this,i)
				}
			)

		};

		drawControlPoints();

		coordinateSprite = document.getElementsByTagName('svg')[1];
		coordinateSprite.style.width = 2*(radius/2) +"px";
		coordinateSprite.style.height = 2*(radius/2) +"px";	

		t = 0;
		update(0);
	
	}

	function drawControlPoints() {
		// draw the control points and connection between 2 consecutive points

		// Erase the existing control points from the canvas

		ctx[1].clearRect ( 0 , 0 , ctx[1].canvas.width, ctx[1].canvas.height );


		for (var i = 0; i < cPoints.length; i++) {
			// First draw the line, you want to draw a filled circle over it
			if ( i < cPoints.length - 1 ) {
				drawLine(ctx[1], cPoints[i], cPoints[i+1]) ;
			}
			drawCircle(ctx[1], cPoints[i], radius/2, true);
			drawCircle(ctx[1], cPoints[i], radius, false);
		};
	}

	var update = function (t1) {
		// If t hasn't changed, assume we're only updating the controlpoints, not the
		// mark left by the coordinateSprite

		// Recalculate weights
		for (var i = 0; i < cPoints.length; i++) {
			w[i] = basisF(i,t1);

			// Display the weights per control point
			cPoints[i].weightSprite.innerHTML = w[i].toFixed(2);

		};
		
		var last_point;
		if (point_on_curve) {
			last_point = point_on_curve;
			point_on_curve = explicitFormula(t1);
		}
		else {
			point_on_curve = explicitFormula(t1);
			last_point = point_on_curve;
		}

		coordinateSprite.style.left = point_on_curve.x - radius/2 + "px";
		coordinateSprite.style.top = point_on_curve.y - radius/2 + "px";
		
		if ( t !== t1 ) {
			// Draw the points (line) of the curve
			ctx[0].beginPath();
			// ctx[0].arc(point_on_curve.x, point_on_curve.y, 0.7, 0, 2*Math.PI);
			ctx[0].moveTo(last_point.x, last_point.y)
			ctx[0].lineTo(point_on_curve.x, point_on_curve.y)
			ctx[0].stroke();
			// ctx[0].endPath();
		}

		t = t1;		
	};

	/**
	 * Create explicit formula for this Bezier curve.
	 * @return function
	 */
	var createExplicitFormula = function () {
		
		return (function(t) {
				var x = 0, y =0, m;

	 			for (var i = 0; i < cPoints.length; i++) {
					m = basisF(i,t);
					x += m * cPoints[i].x;
					y += m * cPoints[i].y;
				};

				return {x: x, y: y};
			}
		);
	};

	return {
		init: init,
		update: update
	};
}

var Slider = function() {
	var d, sprite,
			parameter_box_sprite,
			parameter_number_sprite,
			w, h, 
			minX, maxX;

	var init = function (ctx, callback) {
		// Only needed once at startup
		// After that use reset, to put the slider in it's original position
		// or redraw, to adjust the chrome to screen dimensions

		w = ctx.canvas.width,
		h = ctx.canvas.height;

		minX = floor(w/4);
		maxX = floor(3 * w/4);

		sprite = document.getElementsByTagName('svg')[0];
		parameter_box_sprite = document.getElementById('parameter');
		parameter_number_sprite = parameter_box_sprite.getElementsByTagName('span')[0];

		draw(ctx);

		//TODO
		radius_inner = 20;

		d = new Draggable(sprite, 
				{	type: 'x', 
				bounds:{minX: 0, maxX:maxX - minX},
				onDrag: function() {
					var t = this.x / (maxX - minX);
					parameter_box_sprite.style.left = minX - radius_inner + this.x + "px";
					parameter_number_sprite.innerHTML = t.toPrecision(2);
					callback(t);
				}
			}
		);
	};

	var draw = function (ctx) {
		var radius_outer = 40,
				radius_inner = 20;
		
		var q1 = {x: minX, y: floor(h * 4/5) };
		var q2 = {x: maxX, y: floor(h * 4/5)};

		drawLine(ctx, q1,q2);

		drawCircle(ctx, q1, radius_inner, true);
		drawCircle(ctx, q1, radius_outer, false);
		drawCircle(ctx, q2, radius_inner, true);
		drawCircle(ctx, q2, radius_outer, false);

		// reset sprites
		sprite.style.left = q1.x - radius_inner + "px";
		sprite.style.top = q1.y - radius_inner + "px";
		sprite.style.width = 2*(radius_inner) +"px";
		sprite.style.height = 2*(radius_inner) +"px";

		parameter_box_sprite.style.left = q1.x - radius_inner + "px";
		parameter_box_sprite.style.top = q1.y + radius_inner*3 +"px";

		// Reset draggable
		TweenMax.set(sprite,{x:0});

		parameter_number_sprite.innerHTML = (0).toPrecision(2);
	}

	return {
		init: init,
		draw : draw
	};
};

// graphics
var drawCircle = function(ctx, p, radius, fill) {
	ctx.beginPath();
	ctx.arc(p.x, p.y, radius, 0, 2*Math.PI);
	ctx.lineWidth = 5;
	ctx.stroke();
	if ( fill === true ) ctx.fill();
}

var drawLine = function(ctx, p, q) {
	ctx.beginPath();
	ctx.moveTo(p.x, p.y);
	ctx.lineTo(q.x, q.y);
	ctx.lineWidth = 1;
	ctx.stroke();
}

// Util
var rand = function(min, max) {
	return min + random() * (max - min);
	// return floor(min + random() * (max+1 - min));	
};

/**
 * Calculate binomial coefficients
 * Recursion: Pascal's recurrence
 * Arguments must be integers >= 0, not checked
 * @param  {int} n 
 * @param  {int} k 
 * @return {int}  
 */
var binomial = function (n, k) {
	if (k == 0){
		return 1;
	}
	else if (n == 0) {
		return 0;
	}
	else {
		return binomial(n-1, k-1) + binomial(n-1,k);
	}
}


/**
 * Create basis function(s)
 * Also known as Bernstein basis polynomials
 * @param  {@int} order number of basis functions
 * @return {function} 
 */
function createBasis(order) {
	// Calculate and store binomial coefficients
	var b =[];
	for (var i = 0; i <= order; i++) {
		b[i] = binomial(order, i);
	}

	return (function(i,t){return b[i] * pow(1-t, order-i) * pow(t,i)});
}

Object.getOwnPropertyNames(Math).map(function(p) {
  window[p] = Math[p];
});

function fadeCanvas(ctx, d) {
	TweenMax.to(ctx.canvas, d, {opacity:0, onComplete: 
		function(){
			ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
			ctx.canvas.style.opacity = 1;
		}
	});
}
              
            
!
999px

Console