JavaScript preprocessors can help make authoring JavaScript easier and more convenient. For instance, CoffeeScript can help prevent easy-to-make mistakes and offer a cleaner syntax and Babel can bring ECMAScript 6 features to browsers that only support ECMAScript 5.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
HTML Settings
Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.
<div class="container">
<canvas></canvas>
</div>
html { height: 100%; }
body {
min-height: 100%;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
background: #FED;
font-family: sans-serif;
text-align: center;
}
canvas {
display: block;
margin: 0px auto 20px;
cursor: move;
}
// Hi! This 3D model was built using the <canvas> 2D drawing API.
// I'm working on a library to make these sort of 3D illustrations,
// But it's not ready for prime-time. Stay tuned! *~ dd ~*
// -------------------------- utils -------------------------- //
var TAU = Math.PI * 2;
function extend( a, b ) {
for ( var prop in b ) {
a[ prop ] = b[ prop ];
}
return a;
}
function lerp( a, b, t ) {
return ( b - a ) * t + a;
}
function modulo( num, div ) {
return ( ( num % div ) + div ) % div;
}
// -------------------------- Vector3 -------------------------- //
function Vector3( position ) {
this.set( position );
}
Vector3.prototype.set = function( pos ) {
pos = Vector3.sanitize( pos );
this.x = pos.x;
this.y = pos.y;
this.z = pos.z;
return this;
};
Vector3.prototype.rotate = function( rotation ) {
if ( !rotation ) {
return;
}
this.rotateZ( rotation.z );
this.rotateY( rotation.y );
this.rotateX( rotation.x );
return this;
};
Vector3.prototype.rotateZ = function( angle ) {
rotateProperty( this, angle, 'x', 'y' );
};
Vector3.prototype.rotateX = function( angle ) {
rotateProperty( this, angle, 'y', 'z' );
};
Vector3.prototype.rotateY = function( angle ) {
rotateProperty( this, angle, 'x', 'z' );
};
function rotateProperty( vec, angle, propA, propB ) {
if ( angle % TAU === 0 ) {
return;
}
var cos = Math.cos( angle );
var sin = Math.sin( angle );
var a = vec[ propA ];
var b = vec[ propB ];
vec[ propA ] = a*cos - b*sin;
vec[ propB ] = b*cos + a*sin;
}
Vector3.prototype.add = function( vec ) {
if ( !vec ) {
return;
}
vec = Vector3.sanitize( vec );
this.x += vec.x;
this.y += vec.y;
this.z += vec.z;
return this;
};
Vector3.prototype.subtract = function( vec ) {
if ( !vec ) {
return;
}
vec = Vector3.sanitize( vec );
this.x -= vec.x;
this.y -= vec.y;
this.z -= vec.z;
return this;
};
Vector3.prototype.multiply = function( vec ) {
if ( !vec ) {
return;
}
vec = Vector3.sanitize( vec );
this.x *= vec.x;
this.y *= vec.y;
this.z *= vec.z;
return this;
};
Vector3.prototype.transform = function( translation, rotation, scale ) {
this.multiply( scale );
this.rotate( rotation );
this.add( translation );
};
Vector3.prototype.lerp = function( vec, t ) {
this.x = lerp( this.x, vec.x, t );
this.y = lerp( this.y, vec.y, t );
this.z = lerp( this.z, vec.z, t );
return this;
};
// ----- utils ----- //
// add missing properties
Vector3.sanitize = function( vec ) {
vec = vec || {};
vec.x = vec.x || 0;
vec.y = vec.y || 0;
vec.z = vec.z || 0;
return vec;
};
// -------------------------- Anchor -------------------------- //
function Anchor( options ) {
this.create( options );
}
Anchor.prototype.create = function( options ) {
// set defaults & options
extend( this, this.constructor.defaults );
options = options || {};
this.setOptions( this, options );
// transform
this.translate = new Vector3( options.translate );
this.rotate = new Vector3( options.rotate );
var scale = extend( { x: 1, y: 1, z: 1 }, options.scale );
this.scale = new Vector3( scale );
// origin
this.origin = new Vector3();
this.renderOrigin = new Vector3();
// children
this.children = [];
if ( this.addTo ) {
this.addTo.addChild( this );
}
};
Anchor.defaults = {};
Anchor.optionKeys = Object.keys( Anchor.defaults ).concat([
'rotate',
'translate',
'scale',
'addTo',
]);
Anchor.prototype.setOptions = function( item, options ) {
var optionKeys = this.constructor.optionKeys;
for ( var key in options ) {
if ( optionKeys.includes( key ) ) {
item[ key ] = options[ key ];
}
}
};
Anchor.prototype.addChild = function( shape ) {
this.children.push( shape );
};
// ----- update ----- //
Anchor.prototype.update = function() {
// update self
this.reset();
// update children
this.children.forEach( function( child ) {
child.update();
});
this.transform( this.translate, this.rotate, this.scale );
};
Anchor.prototype.reset = function() {
this.renderOrigin.set( this.origin );
};
Anchor.prototype.transform = function( translation, rotation, scale ) {
this.renderOrigin.transform( translation, rotation, scale );
// transform children
this.children.forEach( function( child ) {
child.transform( translation, rotation, scale );
});
};
Anchor.prototype.updateGraph = function() {
this.update();
this.checkFlatGraph();
this.flatGraph.forEach( function( item ) {
item.updateSortValue();
});
// z-sort
this.flatGraph.sort( sortBySortValue );
};
function sortBySortValue( a, b ) {
return b.sortValue - a.sortValue;
}
Anchor.prototype.checkFlatGraph = function() {
if ( !this.flatGraph ) {
this.updateFlatGraph();
}
};
Anchor.prototype.updateFlatGraph = function() {
this.flatGraph = this.getFlatGraph();
};
// return Array of self & all child graph items
Anchor.prototype.getFlatGraph = function() {
var flatGraph = [ this ];
this.children.forEach( function( child ) {
var childFlatGraph = child.getFlatGraph();
flatGraph = flatGraph.concat( childFlatGraph );
});
return flatGraph;
};
Anchor.prototype.updateSortValue = function() {
this.sortValue = this.renderOrigin.z;
};
// ----- render ----- //
Anchor.prototype.render = function() {};
Anchor.prototype.renderGraph = function( ctx ) {
this.checkFlatGraph();
this.flatGraph.forEach( function( item ) {
item.render( ctx );
});
};
// ----- misc ----- //
Anchor.prototype.copy = function( options ) {
// copy options
var itemOptions = {};
var optionKeys = this.constructor.optionKeys;
optionKeys.forEach( function( key ) {
itemOptions[ key ] = this[ key ];
}, this );
// add set options
this.setOptions( itemOptions, options );
var ItemClass = this.constructor;
return new ItemClass( itemOptions );
};
Anchor.prototype.normalizeRotate = function() {
this.rotate.x = modulo( this.rotate.x, TAU );
this.rotate.y = modulo( this.rotate.y, TAU );
this.rotate.z = modulo( this.rotate.z, TAU );
};
// ----- subclass ----- //
function getSubclass( Super ) {
return function( defaults ) {
// create constructor
function Item( options ) {
this.create( options );
}
Item.prototype = Object.create( Super.prototype );
Item.prototype.constructor = Item;
Item.defaults = extend( {}, Super.defaults );
Item.defaults = extend( Item.defaults, defaults );
Item.optionKeys = Super.optionKeys.slice(0)
.concat( Object.keys( Item.defaults ) );
Item.subclass = getSubclass( Item );
return Item;
};
}
Anchor.subclass = getSubclass( Anchor );
// -------------------------- PathAction -------------------------- //
function PathAction( method, points, previousPoint ) {
this.method = method;
this.points = points.map( mapVectorPoint );
this.renderPoints = points.map( mapVectorPoint );
this.previousPoint = previousPoint;
this.endRenderPoint = this.renderPoints[ this.renderPoints.length - 1 ];
// arc actions come with previous point & corner point
// but require bezier control points
if ( method == 'arc' ) {
this.controlPoints = [ new Vector3(), new Vector3() ];
}
}
function mapVectorPoint( point ) {
return new Vector3( point );
}
PathAction.prototype.reset = function() {
// reset renderPoints back to orignal points position
var points = this.points;
this.renderPoints.forEach( function( renderPoint, i ) {
var point = points[i];
renderPoint.set( point );
});
};
PathAction.prototype.transform = function( translation, rotation, scale ) {
this.renderPoints.forEach( function( renderPoint ) {
renderPoint.transform( translation, rotation, scale );
});
};
PathAction.prototype.render = function( ctx ) {
this[ this.method ]( ctx );
};
PathAction.prototype.move = function( ctx ) {
var point = this.renderPoints[0];
ctx.moveTo( point.x, point.y );
};
PathAction.prototype.line = function( ctx ) {
var point = this.renderPoints[0];
ctx.lineTo( point.x, point.y );
};
PathAction.prototype.bezier = function( ctx ) {
var cp0 = this.renderPoints[0];
var cp1 = this.renderPoints[1];
var end = this.renderPoints[2];
ctx.bezierCurveTo( cp0.x, cp0.y, cp1.x, cp1.y, end.x, end.y );
};
PathAction.prototype.arc = function( ctx ) {
var prev = this.previousPoint;
var corner = this.renderPoints[0];
var end = this.renderPoints[1];
var cp0 = this.controlPoints[0];
var cp1 = this.controlPoints[1];
cp0.set( prev ).lerp( corner, 9/16 );
cp1.set( end ).lerp( corner, 9/16 );
ctx.bezierCurveTo( cp0.x, cp0.y, cp1.x, cp1.y, end.x, end.y );
};
// -------------------------- Shape -------------------------- //
var Shape = Anchor.subclass({
stroke: true,
fill: false,
color: 'black',
lineWidth: 1,
closed: true,
rendering: true,
path: [ {} ],
front: { z: -1 },
});
var protoCreate = Anchor.prototype.create;
Shape.prototype.create = function( options ) {
Anchor.prototype.create.call( this, options );
this.updatePath(); // hook for Rect, Ellipse, & other subclasses
this.updatePathActions();
// front
this.front = new Vector3( options.front || this.front );
this.renderFront = new Vector3( this.front );
this.renderNormal = new Vector3();
};
var defaultShapeKeys = Object.keys( Shape.defaults );
Shape.optionKeys = Shape.optionKeys.concat( defaultShapeKeys ).concat([
'width',
'height',
'front',
'backfaceHidden',
]);
var actionNames = [
'move',
'line',
'bezier',
'arc',
];
Shape.prototype.updatePath = function() {};
// parse path into PathActions
Shape.prototype.updatePathActions = function() {
var previousPoint;
this.pathActions = this.path.map( function( pathPart, i ) {
// pathPart can be just vector coordinates -> { x, y, z }
// or path instruction -> { arc: [ {x0,y0,z0}, {x1,y1,z1} ] }
var keys = Object.keys( pathPart );
var method = keys[0];
var points = pathPart[ method ];
var isInstruction = keys.length === 1 && actionNames.includes( method ) &&
Array.isArray( points );
if ( !isInstruction ) {
method = 'line';
points = [ pathPart ];
}
// first action is always move
method = i === 0 ? 'move' : method;
// arcs require previous last point
var pathAction = new PathAction( method, points, previousPoint );
// update previousLastPoint
previousPoint = pathAction.endRenderPoint;
return pathAction;
});
};
// ----- update ----- //
Shape.prototype.reset = function() {
this.renderOrigin.set( this.origin );
this.renderFront.set( this.front );
// reset pathAction render points
this.pathActions.forEach( function( pathAction ) {
pathAction.reset();
});
};
Shape.prototype.transform = function( translation, rotation, scale ) {
// TODO, only transform these if backfaceHidden for perf?
this.renderOrigin.transform( translation, rotation, scale );
this.renderFront.transform( translation, rotation, scale );
this.renderNormal.set( this.renderOrigin ).subtract( this.renderFront );
// transform points
this.pathActions.forEach( function( pathAction ) {
pathAction.transform( translation, rotation, scale );
});
// transform children
this.children.forEach( function( child ) {
child.transform( translation, rotation, scale );
});
};
Shape.prototype.updateSortValue = function() {
var sortValueTotal = 0;
this.pathActions.forEach( function( pathAction ) {
sortValueTotal += pathAction.endRenderPoint.z;
});
// average sort value of all points
// def not geometrically correct, but works for me
this.sortValue = sortValueTotal / this.pathActions.length;
};
// ----- render ----- //
Shape.prototype.render = function( ctx ) {
var length = this.pathActions.length;
if ( !this.rendering || !length ) {
return;
}
// hide backface
var isFacingBack = this.renderNormal.z > 0;
if ( this.backfaceHidden && isFacingBack ) {
return;
}
// render dot or path
var isDot = length == 1;
if ( isDot ) {
this.renderDot( ctx );
} else {
this.renderPath( ctx );
}
};
// Safari does not render lines with no size, have to render circle instead
Shape.prototype.renderDot = function( ctx ) {
ctx.fillStyle = this.color;
var point = this.pathActions[0].endRenderPoint;
ctx.beginPath();
var radius = this.lineWidth/2;
ctx.arc( point.x, point.y, radius, 0, TAU );
ctx.fill();
};
Shape.prototype.renderPath = function( ctx ) {
// set render properties
ctx.fillStyle = this.color;
ctx.strokeStyle = this.color;
ctx.lineWidth = this.lineWidth;
// render points
ctx.beginPath();
this.pathActions.forEach( function( pathAction ) {
pathAction.render( ctx );
});
var isTwoPoints = this.pathActions.length == 2 &&
this.pathActions[1].method == 'line';
if ( !isTwoPoints && this.closed ) {
ctx.closePath();
}
if ( this.stroke ) {
ctx.stroke();
}
if ( this.fill ) {
ctx.fill();
}
};
// -------------------------- Ellipse -------------------------- //
var Ellipse = Shape.subclass({
width: 1,
height: 1,
closed: false,
});
Ellipse.prototype.updatePath = function() {
var x = this.width / 2;
var y = this.height / 2;
this.path = [
{ x: 0, y: -y },
{ arc: [ // top right
{ x: x, y: -y },
{ x: x, y: 0 },
]},
{ arc: [ // bottom right
{ x: x, y: y },
{ x: 0, y: y },
]},
{ arc: [ // bottom left
{ x: -x, y: y },
{ x: -x, y: 0 },
]},
{ arc: [ // bottom left
{ x: -x, y: -y },
{ x: 0, y: -y },
]},
];
};
// -------------------------- Group -------------------------- //
var Group = Anchor.subclass({
updateSort: false,
});
// ----- update ----- //
Group.prototype.updateSortValue = function() {
var sortValueTotal = 0;
this.checkFlatGraph();
this.flatGraph.forEach( function( item ) {
item.updateSortValue();
sortValueTotal += item.sortValue;
});
// average sort value of all points
// def not geometrically correct, but works for me
this.sortValue = sortValueTotal / this.flatGraph.length;
if ( this.updateSort ) {
this.flatGraph.sort( function( a, b ) {
return b.sortValue - a.sortValue;
});
}
};
// ----- render ----- //
Group.prototype.render = function( ctx ) {
this.checkFlatGraph();
this.flatGraph.forEach( function( item ) {
item.render( ctx );
});
};
// do not include children, group handles rendering & sorting internally
Group.prototype.getFlatGraph = function() {
return [ this ];
};
Group.prototype.checkFlatGraph = function() {
if ( !this.flatGraph ) {
this.updateFlatGraph();
}
};
Group.prototype.updateFlatGraph = function() {
this.flatGraph = this.getChildFlatGraph();
};
// get flat graph only used for group
// do not include in parent flatGraphs
Group.prototype.getChildFlatGraph = function() {
// do not include self
var flatGraph = [];
this.children.forEach( function( child ) {
var childFlatGraph = child.getFlatGraph();
flatGraph = flatGraph.concat( childFlatGraph );
});
return flatGraph;
};
// -------------------------- Dragger -------------------------- //
// quick & dirty drag event stuff
// messes up if multiple pointers/touches
// event support, default to mouse events
var downEvent = 'mousedown';
var moveEvent = 'mousemove';
var upEvent = 'mouseup';
if ( window.PointerEvent ) {
// PointerEvent, Chrome
downEvent = 'pointerdown';
moveEvent = 'pointermove';
upEvent = 'pointerup';
} else if ( 'ontouchstart' in window ) {
// Touch Events, iOS Safari
downEvent = 'touchstart';
moveEvent = 'touchmove';
upEvent = 'touchend';
}
function noop() {}
function Dragger( options ) {
this.startElement = options.startElement;
this.onPointerDown = options.onPointerDown || noop;
this.onPointerMove = options.onPointerMove || noop;
this.onPointerUp = options.onPointerUp || noop;
this.startElement.addEventListener( downEvent, this );
}
Dragger.prototype.handleEvent = function( event ) {
var method = this[ 'on' + event.type ];
if ( method ) {
method.call( this, event );
}
};
Dragger.prototype.onmousedown =
Dragger.prototype.onpointerdown = function( event ) {
this.pointerDown( event, event );
};
Dragger.prototype.ontouchstart = function( event ) {
this.pointerDown( event, event.changedTouches[0] );
};
Dragger.prototype.pointerDown = function( event, pointer ) {
event.preventDefault();
this.dragStartX = pointer.pageX;
this.dragStartY = pointer.pageY;
window.addEventListener( moveEvent, this );
window.addEventListener( upEvent, this );
this.onPointerDown( pointer );
};
Dragger.prototype.ontouchmove = function( event ) {
// HACK, moved touch may not be first
this.pointerMove( event, event.changedTouches[0] );
};
Dragger.prototype.onmousemove =
Dragger.prototype.onpointermove = function( event ) {
this.pointerMove( event, event );
};
Dragger.prototype.pointerMove = function( event, pointer ) {
event.preventDefault();
var moveX = pointer.pageX - this.dragStartX;
var moveY = pointer.pageY - this.dragStartY;
this.onPointerMove( pointer, moveX, moveY );
};
Dragger.prototype.onmouseup =
Dragger.prototype.onpointerup =
Dragger.prototype.ontouchend =
Dragger.prototype.pointerUp = function( event ) {
window.removeEventListener( moveEvent, this );
window.removeEventListener( upEvent, this );
this.onPointerUp( event );
};
// -------------------------- hemisphere -------------------------- //
function hemisphere( options ) {
var group = new Group({
addTo: options.addTo,
rotate: options.rotate,
translate: options.translate,
scale: options.scale,
});
// inside face
var face = new Ellipse({
width: options.size,
height: options.size,
addTo: group,
color: options.insideColor || options.color,
lineWidth: options.lineWidth,
stroke: options.stroke,
fill: options.fill,
backfaceHidden: true,
});
// outside face
var outsideColor = options.outsideColor || options.color;
face.copy({
color: options.outsideColor || options.color,
rotate: { y: TAU/2 },
});
// ----- dome ----- //
group.render = function( ctx ) {
// render dome
var contourAngle = Math.atan2( face.renderNormal.y, face.renderNormal.x );
var startAngle = contourAngle + TAU/4;
var endAngle = contourAngle - TAU/4;
ctx.strokeStyle = ctx.fillStyle = outsideColor;
ctx.lineWidth = options.lineWidth;
ctx.beginPath();
var x = group.renderOrigin.x;
var y = group.renderOrigin.y;
ctx.arc( x, y, options.size/2, startAngle, endAngle );
ctx.closePath();
if ( options.stroke ) {
ctx.stroke();
}
if ( options.fill ) {
ctx.fill();
}
Group.prototype.render.call( this, ctx );
};
}
// -------------------------- demo -------------------------- //
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var w = 48;
var h = 48;
var minWindowSize = Math.min( window.innerWidth, window.innerHeight );
var zoom = Math.min( 10, Math.floor( minWindowSize / w ) );
var pixelRatio = window.devicePixelRatio || 1;
zoom *= pixelRatio;
var canvasWidth = canvas.width = w * zoom;
var canvasHeight = canvas.height = h * zoom;
// set canvas screen size
if ( pixelRatio > 1 ) {
canvas.style.width = canvasWidth / pixelRatio + 'px';
canvas.style.height = canvasHeight / pixelRatio + 'px';
}
var isRotating = true;
var t = 0;
var cycleFrame = 360;
// colors
var yellow = '#ED0';
var gold = '#EA0';
var orange = '#E62';
var magenta = '#C25';
var navy = '#249';
// -- illustration shapes --- //
var scene = new Anchor();
// ----- ----- //
hemisphere({
size: 13,
addTo: scene,
translate: { y: 16 },
rotate: { x: -TAU/4 },
insideColor: navy,
outsideColor: magenta,
stroke: false,
fill: true,
});
hemisphere({
size: 13,
addTo: scene,
translate: { y: -16 },
rotate: { x: TAU/4 },
insideColor: navy,
outsideColor: magenta,
stroke: false,
fill: true,
});
var colorWheel = [ navy, magenta, orange, gold, yellow, ];
[ -1, 1 ].forEach( function( ySide ) {
for ( var i=0; i < 5; i++ ) {
var rotor1 = new Anchor({
addTo: scene,
rotate: { y: TAU/5 * i },
});
var rotor2 = new Anchor({
addTo: rotor1,
rotate: { x: TAU/6 },
});
hemisphere({
size: 13,
addTo: rotor2,
translate: { y: -16*ySide },
rotate: { x: TAU/4*ySide },
outsideColor: colorWheel[i],
insideColor: colorWheel[ (i+7) % 5 ],
stroke: false,
fill: true,
});
}
});
// -- animate --- //
function easeInOut( i ) {
var isFirstHalf = i < 0.5;
var i1 = isFirstHalf ? i : 1 - i;
i1 = i1 / 0.5;
// make easing steeper with more multiples
var i2 = i1 * i1 * i1;
i2 = i2 / 2;
return isFirstHalf ? i2 : i2*-1 + 1;
}
function animate() {
update();
render();
requestAnimationFrame( animate );
}
animate();
// -- update -- //
function update() {
if ( isRotating ) {
t += 1/cycleFrame;
t = t % 1;
var isFirstHalf = t < 0.5;
var halfT = isFirstHalf ? t : t - 0.5;
var doubleEaseT = easeInOut( halfT * 2 ) / 2;
doubleEaseT += isFirstHalf ? 0 : 0.5;
scene.rotate.y = doubleEaseT * TAU;
scene.rotate.x = Math.cos( doubleEaseT * TAU ) * TAU/12;
}
scene.updateGraph();
}
// -- render -- //
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
function render() {
ctx.clearRect( 0, 0, canvasWidth, canvasHeight );
ctx.save();
ctx.scale( zoom, zoom );
ctx.translate( w/2, h/2 );
scene.renderGraph( ctx );
ctx.restore();
}
// ----- inputs ----- //
// click drag to rotate
var dragStartAngleX, dragStartAngleY;
new Dragger({
startElement: canvas,
onPointerDown: function() {
isRotating = false;
dragStartAngleX = scene.rotate.x;
dragStartAngleY = scene.rotate.y;
},
onPointerMove: function( pointer, moveX, moveY ) {
var angleXMove = moveY / canvasWidth * TAU;
var angleYMove = moveX / canvasWidth * TAU;
scene.rotate.x = dragStartAngleX + angleXMove;
scene.rotate.y = dragStartAngleY + angleYMove;
},
});
Also see: Tab Triggers