Skip to content

Instantly share code, notes, and snippets.

@jcblw
Created August 16, 2015 20:06
Show Gist options
  • Save jcblw/3887b32d574ed228af38 to your computer and use it in GitHub Desktop.
Save jcblw/3887b32d574ed228af38 to your computer and use it in GitHub Desktop.
requirebin sketch
const body = document.body
const vsvg = require('vsvg')
const width = window.innerWidth
const height = window.innerHeight
const svg = vsvg.svg({width: width + 'px', height: height + 'px'})
const paths = require('vsvg-paths')
function pathGen() {
return paths.encode([
{
x: 0,
y: height / 2
},
{
x: width,
y: height / 2,
x2: Math.random() * width,
y2: Math.random() * height
}
])
}
function svgAnimation(id) {
const ogPath = pathGen()
const values = [ogPath]
for (var i = 0; i < 100; i += 1) {
values.push(pathGen())
}
values.push(ogPath)
return vsvg.animate({
'xlink:href': '#p' + id,
attributeType:'XML',
attributeName: 'd',
values: values.join('; '),
dur: '50s',
repeatCount: 'indefinite',
fill: 'freeze'})
}
function svgPath(id, color) {
return vsvg.path({
d: pathGen(),
stroke: color,
'stroke-width': 2,
fill: 'transparent',
id: 'p' + id})
}
const colors = ['tomato', 'dodgerblue', 'rebeccapurple', 'tomato', 'dodgerblue', 'rebeccapurple', 'tomato', 'dodgerblue', 'rebeccapurple' ]
const elems = [];
for (var i = 0; i < colors.length; i += 1) {
elems.push(svgPath(i, colors[i]));
elems.push(svgAnimation(i));
}
elems.unshift({width: width + 'px', height: height + 'px',xmlns:'http://www.w3.org/2000/svg', 'xmlns:xlink':'http://www.w3.org/1999/xlink', version:'1.1', viewBox: '0 0 ' + width + ' ' + height});
document.body.appendChild(vsvg.svg.apply(vsvg, elems)._node);
require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){"use strict";var startTag=/^<([-A-Za-z0-9_:]+)(.*?)(\/?)>/g,endTag=/<\/([-A-Za-z0-9_:]+)[^>]*>/,docTag=/^<(\?)(.*?)(\/?)>/g,commentTag=/^<(\!--)(.*?)(\/?)>/g,attr=/([-A-Za-z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g;exports.parse=parse;function makeArray(arr){return Array.prototype.slice.call(arr,0)}var getAttributes=exports.getAttributes=function getAttributes(attributes){var _attributes={};function addToAttributes(keyvalue){var arr=keyvalue.split(/=/),key=arr[0],value=arr[1]?arr[1].slice(1).slice(0,-1):"";_attributes[key]=value}attributes.forEach(addToAttributes);return _attributes};var getTagIndex=exports.getTagIndex=function getTagIndex(tagName,tags){for(var i=tags.length-1;i>=0;i-=1){if(tags[i].tagName===tagName){return i}}return-1};var getLastOpenTag=exports.getLastOpenTag=function getLastOpenTag(tags){for(var i=tags.length-1;i>=0;i-=1){if(!tags[i].closed){return i}}return-1};var createTree=exports.createTree=function createTree(tags){var _tags=[];function getArray(position,arr){var _position=makeArray(position);if(_position.length===1){return arr}var next=arr[_position[0]].children;_position.shift();return getArray(_position,next)}function addTagToTree(tag){var arr=getArray(tag.position,_tags);arr.push(tag)}tags.forEach(addTagToTree);return _tags};function parse(xml){xml=xml.replace(/(\r\n|\n|\r)/gm,"");var tags=[],position=[-1],openTag,attributes,end,text,index,prevTag,prevLength,closed,tagName,tag,specialTag;while(xml){if(xml.length===prevLength){throw new Error("Failed to parse SVG at chars: "+xml.substring(0,5))}prevLength=xml.length;xml=xml.trim();openTag=xml.match(startTag);specialTag=xml.match(docTag)||xml.match(commentTag);if(openTag){openTag=openTag[0];attributes=openTag.match(attr);xml=xml.substring(openTag.length);text=null;prevTag=null;closed=null;if(/\/>$/.test(openTag)){closed=true}}else if(specialTag){xml=xml.substring(specialTag[0].length);attributes=[]}else{end=xml.match(endTag);attributes=[];if(end){index=getTagIndex(end[1],tags);prevTag=tags[index];text=xml.slice(0,end.index);xml=xml.substring(end.index+end[0].length)}}tagName=attributes.shift();if(tagName||text){tag={tagName:tagName,attributes:getAttributes(attributes),children:[],text:text,inside:getLastOpenTag(tags),closed:closed||!!text};if(tag.inside>-1){position.push(-1);position[tags[tag.inside].position.length]+=1;position=position.slice(0,tags[tag.inside].position.length+1)}else{position[0]+=1}tag.position=makeArray(position);tags.push(tag)}if(prevTag){prevTag.closed=true}}return createTree(tags)}},{}],2:[function(require,module,exports){"use strict";var tags=require("./tags"),SvgNode=require("./svgNode"),parser=require("vsvg-parser"),methods={};module.exports=function(){tags.forEach(function(tagName){methods[tagName]=SvgNode.bind(null,tagName)});return methods}();var _eachTag=methods._eachTag=function _eachTag(tag){var elem;if(tag.tagName&&methods[tag.tagName]){elem=methods[tag.tagName](tag.attributes);if(elem.children){for(var i=0;i<tag.children.length;i+=1){var _elem=_eachTag(tag.children[i]);if(typeof _elem==="string"){elem.innerText=_elem}else{elem.appendChild(_elem)}}}return elem}return tag.text||""};var parse=methods.parse=function(svg){var parsedSVG;try{parsedSVG=parser.parse(svg)}catch(e){return null}return parsedSVG.map(_eachTag)};var addNodeToVNode=methods._addNodeToVNode=function(node,vNode){function eachChild(_vNode,index){addNodeToVNode(node.children[index],_vNode)}vNode.children.forEach(eachChild);vNode._node=node};methods.mount=function(el){var svg=el.outerHTML,tagTree=parse(svg);addNodeToVNode(el,tagTree[0]);return tagTree[0]}},{"./svgNode":3,"./tags":4,"vsvg-parser":1}],3:[function(require,module,exports){"use strict";var utils=require("./utils"),TextNode=require("./textNode"),namespace="http://www.w3.org/2000/svg";module.exports=SvgNode;function SvgNode(tagName,attributes,vnodes){var rest=utils.makeArray(arguments,2);if(!(this instanceof SvgNode)){return new SvgNode(tagName,attributes,rest)}attributes=Object.create(attributes||{});this.guid=utils.guid();this.tagName=tagName;this._children=[];this.styles=attributes.style?utils.styleToObject(attributes.style):{};attributes.style=this.styles;this._attributes=attributes;if(typeof document==="object"){this._node=document.createElementNS(namespace,tagName);for(var attribute in attributes){var value=attributes[attribute];if(attribute==="style"){value=utils.objToStyles(value)}this._node.setAttribute(attribute,value)}}if(Array.isArray(vnodes)&&vnodes.length){vnodes.filter(SvgNode.isNode).forEach(this.appendChild.bind(this))}}SvgNode.isNode=function(vnode){return vnode instanceof SvgNode};SvgNode.prototype={insertBefore:function(elem,refElem){var index=utils.getElementIndex(refElem,this._children);this.removeChild(elem);this._children.splice(index,0,elem);if(this._node&&elem._node&&refElem._node){this._node.insertBefore(elem._node,refElem._node)}},removeChild:function(elem){var index=utils.getElementIndex(elem,this._children);if(index===-1){return}this._children.splice(index,1);if(this._node&&elem._node){this._node.removeChild(elem._node)}},replaceChild:function(elem,replaceElem){var index=utils.getElementIndex(elem,this._children);if(index===-1){return}this._children.splice(index,1,replaceElem);if(this._node&&elem._node&&replaceElem._node){this._node.replaceChild(replaceElem._node,elem._node)}},appendChild:function(elem){this.removeChild(elem);elem.parentNode=this;this._children.push(elem);if(this._node&&elem._node){this._node.appendChild(elem._node)}},_removeTextNodes:function(node){return!!node.tagName},get children(){return this._children.filter(this._removeTextNodes)},get firstChild(){return this._children[0]},toHTML:function(){return"<"+this.tagName+" "+utils.objToAttributes(this._attributes||{})+">"+this._children.map(utils.mapElementsToHTML).join("")+"</"+this.tagName+">"},toText:function(){return this._children.map(utils.mapElementsToText).join("")},getAttribute:function(key){return this._attributes[key]},setAttribute:function(key,value){this._attributes[key]=value;if(this._node){this._node.setAttribute(key,value)}},get attributes(){return this._attributes},set attributes(value){return value},get outerHTML(){return this.toHTML()},get innerHTML(){return this._children.map(utils.mapElementsToHTML).join("")},set innerHTML(html){var vsvg=require("../");if(this._node){this._node.innerHTML=html;this._children=vsvg.mount(this._node).children}else{this._children=vsvg.parse(html)}},get innerText(){return this.toText()},set innerText(value){this._children.length=0;this._children.push(new TextNode(value,{unsafe:this.tagName==="style"}));if(this._node){this._node.innerText=value}}}},{"../":undefined,"./textNode":5,"./utils":6}],4:[function(require,module,exports){"use strict";module.exports=["a","altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignObject","g","glyph","glyphRef","hkern","image","line","linearGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","span","switch","symbol","text","textPath","title","tref","tspan","use","view","vkern"]},{}],5:[function(require,module,exports){"use strict";var utils=require("./utils");module.exports=TextNode;function TextNode(text,options){if(!(this instanceof TextNode)){return new TextNode(text,options)}options=options||{};this.text=options.unsafe?text:utils.escapeHTML(text)}TextNode.prototype={toHTML:function(){return this.text},toText:function(){return this.text}}},{"./utils":6}],6:[function(require,module,exports){"use strict";function s4(){return Math.floor((1+Math.random())*65536).toString(16).substring(1)}exports.guid=function guid(){return s4()+s4()+"-"+s4()+"-"+s4()+"-"+s4()+"-"+s4()+s4()+s4()};var objToStyles=exports.objToStyles=function objToStyles(styles){var ret="";for(var prop in styles){ret+=prop+":"+styles[prop]+";"}return ret};exports.styleToObject=function styleToObject(styles){var ret={};if(typeof styles==="object"){return styles}styles.split(";").map(keyVal).forEach(addToReturn);function addToReturn(keyval){ret[keyval[0]]=keyval[1]}function keyVal(str){return str.trim().split(":")}return ret};exports.objToAttributes=function objToAttributes(attributes){var ret="",value;for(var attr in attributes){value=attr==="style"?objToStyles(attributes[attr]):attributes[attr];if(attr!=="style"||value){ret+=attr+'="'+value+'" '}}return ret};exports.mapElementsToHTML=function mapElementsToHTML(elem){return elem.toHTML()};exports.mapElementsToText=function mapElementsToText(elem){return elem.toText()};exports.getElementIndex=function getElementIndex(elem,arr){var index=-1;arr.forEach(function(_elem,_index){if(elem.guid===_elem.guid){index=_index}});return index};exports.escapeHTML=function escapeHTML(html){return String(html).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")};exports.makeArray=function makeArray(arr,index){return Array.prototype.slice.call(arr,index||0)}},{}],vsvg:[function(require,module,exports){var vsvg=require("./src/");module.exports=vsvg;if(typeof window==="object"){window.vsvg=vsvg}},{"./src/":2}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){"use strict";var eachInstPattern=/(([a-z]+)((\s?\,?(\-?[0-9]+\.?[0-9]*))+)?)/gi,instPattern=/([a-z]+)|(\-?[0-9]+\.?[0-9]*)/gi,alphastart=/^[A-Z]/i,lengths={V:2,H:2,L:3,M:3,S:5,Q:5,A:8,C:7};module.exports.decode=function decode(pathData){var instructions=pathData.match(eachInstPattern).map(splitInstruction);return unfold(instructions,expandMultiPoints).map(createPoint)};var splitInstruction=module.exports._splitInstruction=function splitInstruction(instruction){return instruction.match(instPattern)};var unfold=module.exports._unfold=function unfold(array,iterator){var accumulator=[];array.forEach(iterator.bind(array,accumulator));return accumulator};var expandMultiPoints=module.exports._expandMultiPoints=function expandMultiPoints(accumulator,instruction){var instruct=instruction[0].toUpperCase(),length=lengths[instruct],next;accumulator.push(instruction);if(typeof length!=="number"||instruction.length<=length){return}next=instruction.slice(length);next.unshift(instruction[0]);expandMultiPoints(accumulator,next)};var createPoint=module.exports._createPoint=function createPoint(instruction){var type=instruction[0].toUpperCase();if(type==="V"){return{y:+instruction[1],rel:instruction[0]!==type}}if(type==="H"){return{x:+instruction[1],rel:instruction[0]!==type}}if(type==="L"||type==="M"){return{x:+instruction[1],y:+instruction[2],rel:instruction[0]!==type}}if(type==="S"){return{x2:+instruction[1],y2:+instruction[2],x:+instruction[3],y:+instruction[4],rel:instruction[0]!==type}}if(type==="Q"){return{x1:+instruction[1],y1:+instruction[2],x:+instruction[3],y:+instruction[4],rel:instruction[0]!==type}}if(type==="A"){return{rx:+instruction[1],ry:+instruction[2],xrotate:+instruction[3],largearc:+instruction[4],sweep:+instruction[5],x:+instruction[6],y:+instruction[7],rel:instruction[0]!==type}}if(type==="C"){return{x1:+instruction[1],y1:+instruction[2],x2:+instruction[3],y2:+instruction[4],x:+instruction[5],y:+instruction[6],rel:instruction[0]!==type}}return{}}},{}],2:[function(require,module,exports){"use strict";var sortValues={x1:0,y1:1,x2:2,y2:3,rx:4,ry:5,xrotate:6,largearc:7,sweep:8,x:9,y:10};module.exports.encode=function encode(path){if(!Array.isArray(path)){return}var instructions=path.map(getInstruction),values;values=path.map(keyValueArray).map(sortPoints).map(stringifyPoints(instructions));return values.join(" ")};var keyValueArray=module.exports._keyValueArray=function keyValueArray(points){var ret=[];for(var key in points){if(!(key==="rel"||key==="relative")){ret.push([key,points[key]])}}return ret};var getValue=module.exports._getValue=function getValue(instr){return function(point,index){return(!index?instr:"")+point[1]}};var sortValue=module.exports._sortValue=function sortValue(prev,cur){return sortValues[prev[0]]-sortValues[cur[0]]};var sortPoints=module.exports._sortPoints=function sortPoints(points){return points.sort(sortValue)};var stringifyPoints=module.exports._stringifyPoints=function stringifyPoints(instructions){return function(point,index){if(!point.length){return instructions[index]}return point.map(getValue(instructions[index])).join(" ")}};var isValid=module.exports._isValid=function isValid(value){if(isNaN(value)){return false}return value||typeof value==="number"};var getInstruction=module.exports._getInstruction=function getInstruction(points,index){var instruction;if(isValid(points.x2)&&isValid(points.y2)&&isValid(points.x1)&&isValid(points.y1)){instruction="C"}if(!instruction&&isValid(points.rx)&&isValid(points.ry)){instruction="A"}if(!instruction&&isValid(points.x1)&&isValid(points.y1)){instruction="Q"}if(!instruction&&isValid(points.x2)&&isValid(points.y2)){instruction="S"}if(!instruction&&isValid(points.x)&&isValid(points.y)){instruction="L";if(!index){instruction="M"}}if(!instruction&&isValid(points.x)){instruction="H"}if(!instruction&&isValid(points.y)){instruction="V"}if(!instruction){instruction="Z"}return points.relative||points.rel?instruction.toLowerCase():instruction}},{}],"vsvg-paths":[function(require,module,exports){module.exports.encode=require("./src/encode").encode;module.exports.decode=require("./src/decode").decode},{"./src/decode":1,"./src/encode":2}]},{},[]);const body=document.body;const vsvg=require("vsvg");const width=window.innerWidth;const height=window.innerHeight;const svg=vsvg.svg({width:width+"px",height:height+"px"});const paths=require("vsvg-paths");function pathGen(){return paths.encode([{x:0,y:height/2},{x:width,y:height/2,x2:Math.random()*width,y2:Math.random()*height}])}function svgAnimation(id){const ogPath=pathGen();const values=[ogPath];for(var i=0;i<100;i+=1){values.push(pathGen())}values.push(ogPath);return vsvg.animate({"xlink:href":"#p"+id,attributeType:"XML",attributeName:"d",values:values.join("; "),dur:"50s",repeatCount:"indefinite",fill:"freeze"})}function svgPath(id,color){return vsvg.path({d:pathGen(),stroke:color,"stroke-width":2,fill:"transparent",id:"p"+id})}const colors=["tomato","dodgerblue","rebeccapurple","tomato","dodgerblue","rebeccapurple","tomato","dodgerblue","rebeccapurple"];const elems=[];for(var i=0;i<colors.length;i+=1){elems.push(svgPath(i,colors[i]));elems.push(svgAnimation(i))}elems.unshift({width:width+"px",height:height+"px",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1",viewBox:"0 0 "+width+" "+height});document.body.appendChild(vsvg.svg.apply(vsvg,elems)._node);
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"vsvg": "1.9.1",
"vsvg-paths": "1.0.0"
}
}
<!-- contents of this file will be placed inside the <body> -->
<!-- contents of this file will be placed inside the <head> -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment