css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

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

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

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.

            
              <header class="container">

  <div class="logo">
    <h1 class="logo__heading">
      <img class="logo__image" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/39255/jpng-logo.png" alt="JPNG.svg" />
    </h1>
    <small class="logo__subtitle"><em>This logo was originally 300kb, but compressed down to 69kb using the tool below.</em></small>

  </div>

  <p class="text-center"><strong>Combine the transparency of a PNG with the compression of a JPEG.</strong></p>
  
  <p>Based on the idea from <a href="http://peterhrynkow.com/how-to-compress-a-png-like-a-jpeg/">Using SVG to Shrink Your PNGs</a>, but adapted to use data URIs instead of external images. Include on your page as inline SVG, using an <code>&lt;img/&gt;</code> tag, or as a <code>background-image</code>.</p>

  <p>This technique is tested & working in all modern browsers, IE9+ and Safari 9+. Run <a href="https://codepen.io/shshaw/pen/IDbqC" target="_blank">the image test</a> yourself to see if it works in required browsers. Inline seems to be the best option for compatibility, in which case you should use external assets so that they can be cached.</p>
  
  
  <p class="text-center"><small><em>Need more SVG? Try <a href="https://codepen.io/shshaw/pen/XbxvNj" target="_top">Pixels.svg</a>, <a href="https://codepen.io/shshaw/pen/doLavv" target="_top">HalfTone.svg</a> and <a href="https://codepen.io/shshaw/pen/BNeBPq">LinePrint.svg</a>.</em></small></p>

  <p class="note">Adjust your settings before dragging & dropping a transparent PNG.<br />
    If you need to change the settings, make your changes then add the file again. <br />
    Photographic PNGs with transparency can be rather large, so processing may take a moment.</p>



<div class="controls">
  <div class="control-group">
    <label class="control">
      <span class="control__label">Image Quality:</span> 
      <input type="range" name="image-quality" min="0.1" max="1" step="0.1" value="0.6" />
      <span class="current-value"></span>
    </label>
  </div>

  <div class="control-group">
    <label class="control">
      <span class="control__label">Image Matte:</span> 
      <input type="color" name="matte" value="#FFFFFF" />
      <span class="current-value"></span>
    </label>
  </div>

  <div class="control-group">
    <div class="control">
      <span class="control__label">Mask Type: </span>
      <label><input type="radio" name="mask-type" value="jpeg" checked/> JPEG</label>
      <label><input type="radio" name="mask-type" value="png" /> PNG</label>
    </div>

    <label class="control">
      <span class="control__label">Mask Quality: </span>
      <input type="range" name="mask-quality" min="0.1" max="1" step="0.1" value="0.5" />
      <span class="current-value"></span>
    </label>
  </div>
  </div>

  <div class="choices">
    <div class="file">
      Drag & Drop files or 
      <input type="file" id="upload" multiple="multiple" accept=".jpg,.jpeg,.png,.gif,.svg" />
    </div>

    <button id="test">Try a test image: <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/39255/face.png" id="testImage" crossorigin="anonymous" style="width: 2em" /></button>

    <button id="clear">Clear Output</button>
  </div>
</header>

<div id="output"></div>

<div id="filedrag">Drop images to convert here.</div>

            
          
!
            
              @accent: #f05555;
@accent-light: #FF7777;

@gray-dark: #535050;
@gray: #ddd;
@gray-light: #eaeaea;
@gray-lighter: #f0f0f0;

body { 
  max-width: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  background: @gray-lighter;
  padding: 1em;
  padding-bottom: 2em;
  margin: auto;
  font-size: 14px;
  line-height: 1.4;
}

.text-center { text-align: center; }

.container { margin: 1em auto; max-width: 40em; }
.container:first-child { margin-top: 0; }

.logo { margin-top: 30px; margin-bottom: 30px; }
.logo__heading { 
  margin: 0; 
  padding: 0; 
  position: relative; 

  &:before,
  &:after {
    content: '';
    display: block;
    width: 30%;
    padding-bottom: 30%;
    height: 0;
    
    border-radius: 50% 50% 0 50%;
    background: #FFF;
    box-shadow: 0 0 40px #FFFCDA;
    opacity: 0.95;
    position: absolute;
    bottom: 20%;
    left: -1%;
    top: 0;
    margin: auto;
    z-index: -2;
    animation: spotlight 3s ease-in-out 0s infinite alternate;
    
    transform-origin: 100% 100%;
    
    @keyframes spotlight {
      from { transform: rotate(65deg) scale(1.6, 1) rotate(-45deg); }
      to { transform: rotate(125deg) scale(1.6, 1) rotate(-45deg); }
    }
  }
  
  &:after {
    left: 46%;
    animation-delay: -3.2s;
  }
}
.logo__subtitle { 
    display: block; text-align: center;  }
.logo__image { max-width: 120%; height: auto; margin-left: -10%; margin-right: -10%; margin-bottom: -7%; }

.note { background: #ffee77; font-size: 0.8em; text-align: center; padding: 0.5em; }

h1, h2 { display: block; margin: 0 auto 0.5em; }

h2 { font-size: 1.4em; color: @accent; }
h2 svg { height: 21px; width: auto; margin: 0; }
h2 svg path { stroke: currentColor; }

p { margin: 0 auto 1em; }

a { 
  color: @accent;
  transition: color 250ms ease-in-out;
  &:hover,
  &:focus { color: @accent-light; }
}
img { vertical-align: middle; }
button { 
  background: #ddd;
  border: none;
  appearance: none; 
  cursor: pointer;
}
button, .file { 
  padding: 0.75em;
}


svg, .choices label, input[type=file] { 
  display: block; 
  margin: auto;
  text-align: center;
}
label small { display: block; }

svg { max-width: 100%; }

.choices { 
  background: #eaeaea;
  display: flex;
  align-items: stretch;
  margin: 1em auto;
}

.choices button {
  background: transparent;
  font-size: 0.8em; 
  border-left: solid 3px #aaa;
}

.choices > * { flex: 1 1 auto; }
.file { overflow: hidden; flex-basis: 40%; }

#output { margin: auto auto 2em; text-align: center; }

.output { 
  //display: flex;
  width: 100%;
  margin: 0;
  //justify-content: space-between;
  //align-items: stretch;
  padding: 1em 0;
  border-bottom: solid 3px @gray;
}

.output svg,
.output img {
  max-width: 100%;
  height: auto;
}
.output > a { 
  display: block; 
  outline: solid 1px #aaa;
/*  background: #FFF;
  background-image: linear-gradient(45deg, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%), linear-gradient(45deg, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);
  background-size: 20px 20px;
  background-position: 0 0, 10px 10px;*/
  
  background: #FFF url('data:image/svg+xml;charset=utf-8,%3Csvg xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22 height%3D%2220%22 width%3D%2220%22 fill%3D%22%23ddd%22%3E %3Crect width%3D%2210%22 height%3D%2210%22 x%3D%2210%22 %2F%3E%3Crect width%3D%2210%22 height%3D%2210%22 y%3D%2210%22 %2F%3E %3C%2Fsvg%3E');
  background-size: 15px 15px;
  //width: 50%;
}
.output svg { 
  width: 100%;
  height: auto;
  margin: 1em auto;
}
.output__details { 
  //width: 50%;
  //display: flex;
  //flex-direction: column;
}
.output__raw {
  display: block;
  background: #eaeaea;
  white-space: pre-wrap;
  padding: 0.5em;
  font-size: 0.75em;
  max-height: 20em;
  overflow: auto;
  text-align: left;
}

.output__details {
  font-size: 0.8em;
}

.output__size { display: block; }

.output__details a,
.output__details button { 
  display: inline-block;
  text-align: center;
  margin: 1em 0.25em 0;
  padding: 0.25em 0.5em;
  border: none;
  vertical-align: middle;
  background-color: @accent;
  color: #FFF;
  text-decoration: none;
  
  &:hover,
  &:focus {
    background-color: lighten(@accent,10%);
  }
}

#filedrag { display: none; }
#filedrag.dragenter { 
  position: fixed;
  top: 0; right: 0; bottom: 0; left: 0;
  margin: auto;
  background: #ff5555;
  background: rgba(255,200,200,0.8);
  text-align: center;
  display: block;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  z-index: 999;
}

label { cursor: pointer; }

input[type="range"] {
  width: 60%;
  height: 5px;
  margin: 0;
  border: none;
  //padding: 1px 2px;
  border-radius: 2px;
  background: darken(@gray,10%);
  background-image: linear-gradient(to right, transparent 95%, darken(@gray,30%) 95%);
  background-size: 10.25% 100%;
  background-position: 4.75% 0;
  cursor: grab;
  vertical-align: middle;
  box-shadow: inset 1px 1px 3px darken(@gray,30%);
  outline: none;
  -webkit-appearance: none;
  -webkit-tap-highlight-color: rgba(255, 255, 255, 0);
  
  &:focus:hover {
    cursor: grabbing;
  }
}

input[type="range"]::-moz-range-track {
  border: inherit;
  background: transparent;
}
input[type="range"]::-ms-track {
  border: inherit;
  color: transparent; /* don't drawn vertical reference line */
  background: transparent;
}
input[type="range"]::-ms-fill-lower,
input[type="range"]::-ms-fill-upper { background: transparent; }
input[type="range"]::-ms-tooltip { display: none; }

/* thumb */

.slider-thumb(@rules) {
  input[type="range"]::-webkit-slider-thumb { @rules(); }
  input[type="range"]::-moz-range-thumb { @rules(); }
  input[type="range"]::-ms-thumb { @rules(); }
}

.slider-thumb(@rules,@focus) {
  .slider-thumb(@rules);
  input[type="range"]:focus::-webkit-slider-thumb { @focus(); }
  input[type="range"]:focus::-moz-range-thumb { @focus(); }
  input[type="range"]:focus::-ms-thumb { @focus(); }
}
  
.slider-thumb({
  -webkit-appearance: none;
  margin-top: -1px;
  width: 16px;
  height: 16px;
  border: none;
  border-radius: 50%;
  background: #FFF;
  border: solid 2px @gray-dark;
  transition: all 250ms ease-in-out;
},{ transform: scale(1.25); border-width: 3px; });


.control-group {
  display: block;
  margin-bottom: 0.25em;
}
            
          
!
            
              console.clear();
console.time = console.time || function(){};
console.timeEnd = console.timeEnd || function(){};

(function(){

  "use strict";

  function each(obj,fn) {
    var length = obj.length,
        likeArray = ( length === 0 || ( length > 0 && (length - 1) in obj ) ),
        i = 0;

    if ( likeArray ) {
      for ( ; i < length; i++ ) { if ( fn.call( obj[ i ], i, obj[ i ] ) === false ) { break; } }
    } else {
      for (i in obj) { if ( fn.call( obj[ i ], i, obj[ i ] ) === false ) { break; } }
    }
  }

  function convertImage(img){
    "use strict";

    var window = window || {};
    window.CP = { 
      shouldStopExecution: function(){ return false; },
      exitedLoop: function(){}
    };

    console.log(img.options);

    var data = img.imageData,
        mask = img.mask || img.options.mask,
        dataURL = img.options.matte.dataURL || img.dataURL || img.options.dataURL,
        width = img.naturalWidth || img.width,
        height = img.naturalHeight || img.height,
        output = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 '+width+' '+height+'" width="'+width+'" height="'+height+'">\n<!-- Made with JPNG.svg http://cdpn.io/LVKEdv -->\n';

    // Only output a mask if there is one.
    if ( mask ) { 
      output += '<defs><mask id="a"><image width="'+width+'" height="'+height+'" xlink:href="'+mask.dataURL+'"/></mask></defs>\n';
    }

    output += '<image width="'+width+'" height="'+height+'"' + ( mask ? ' mask="url(#a)"' : '' ) + ' xlink:href="'+dataURL+'"/></svg>';

    // Send message back to the main script
    return output; //;//output;

  };

  function imageDataToAlpha(img,levels) {
    var data = img.data,
        len = data.length,
        alpha = false,
        i = 0, gray;

    // Limit colors to certain amount of levels
    levels = ( levels < 1 && levels > 0 ? levels * 10 : levels ) || false;

    for (; i < len; i+= 4) {
      if ( !alpha && data[i+3] < 255 ) { alpha = true; }
      gray = ( !levels ? data[i+3] : Math.round(data[i+3]/256 * levels) * (256 / levels ) );
      data[i] = data[i+1] = data[i+2] = gray; //data[i+3];
      data[i+3] = 255;
    }

    return ( alpha ? img : false );
  }

  function alphaMask(svggyImage) {

    var img = svggyImage.imageData,
        canvas = document.createElement("canvas"),
        ctx = canvas.getContext("2d"),
        width = img.naturalWidth || img.width,
        height = img.naturalHeight || img.height,
        maskTypeInputChecked = document.querySelector('input[name="mask-type"]:checked'),
        maskType = ( maskTypeInputChecked ? maskTypeInputChecked.value : 'png'),
        maskQualityInput = document.querySelector('input[name="mask-quality"]'),
        maskQuality = ( maskQualityInput ? maskQualityInput.value : 0.3 );

    canvas.width = width;
    canvas.height = height;

    img = imageDataToAlpha(img,( maskType === 'png' && maskQuality < 1 ? maskQuality * 10 : null));

    if ( !img ) { return false; }

    ctx.putImageData(img,0,0);

    return { 
      imageData: img,
      dataURL: canvas.toDataURL('image/'+maskType, parseFloat(maskQuality)),
      quality: maskQuality,
      type: maskType
    };
  }

  function addMatte(svggyImage,quality){

    var img = svggyImage.imageData,
        canvas = document.createElement("canvas"),
        ctx = canvas.getContext("2d"),
        w = img.naturalWidth || img.width,
        h = img.naturalHeight || img.height,
        color = document.querySelector('input[name="matte"]').value || "#000";

    quality = quality || 0.6;

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

    ctx.fillStyle = color;
    ctx.fillRect(0,0,w,h);
    ctx.drawImage(svggyImage.canvas,0,0);

    return { 
      imageData: ctx.getImageData(0,0,w,h),
      dataURL: canvas.toDataURL('image/jpeg', parseFloat(quality))
    };
  }

  // Test Image Conversion
  var test = document.getElementById('test');
  var testImage = document.getElementById('testImage');
  test.onclick = function(){ new SvggyImage(testImage,convert); }

  function convert(){

    var imageQualityInput = document.querySelector('input[name="image-quality"]'),
        imageQuality = ( imageQualityInput ? imageQualityInput.value : 0.6 );

    this.options = {
      dataURL: this.canvas.toDataURL('image/jpeg', parseFloat(imageQuality)),
      matte: addMatte(this,imageQuality),
      mask: alphaMask(this)
    }

    this.process(convertImage,false,showOutput);
  };


  function loadFiles(e){
    var files = (e.target.files || e.dataTransfer.files || uploader.files),
        len = files.length,
        i = 0;

    each(files,function(i,file){
      var reader = new FileReader();

      new SvggyImage(file,convert);
    });

  }

  // File Uploader
  var uploader = document.getElementById('upload');
  uploader.onchange = loadFiles;

  // Drag & Drop
  var fileDrag = document.getElementById('filedrag');

  function FileDragReset(e){
    e.preventDefault();
    fileDrag.className = '';
  }

  function FileDragDrop(e){
    e = e || window.event;
    FileDragReset(e);    
    loadFiles(e);
  }

  fileDrag.addEventListener("dragleave", FileDragReset);
  document.addEventListener("dragenter", function(){ fileDrag.className = 'dragenter'; });
  document.addEventListener('dragover',function(e){ e.preventDefault(); /* Essential! */ });
  document.addEventListener("drop", FileDragDrop);

}());


////////////////////////////////////////

// OUTPUT
(function(){

  // File Output
  var outputDiv = document.getElementById('output');

  if ( !outputDiv ) { 
    outputDiv = document.createElement('div');
    outputDiv.setAttribute('id','output');
    document.body.appendChild('output');
  }

  // Clear Output
  var clear = document.getElementById('clear');
  clear.onclick = function(){ output.innerHTML = ""; };

  function fileSize(str) {
    var bytes = ( typeof str === typeof "" ? encodeURI(str).split(/%..|./).length - 1 : str );
    if ( bytes === 0 ) return 0;
    var sizes = ['bytes', 'kb', 'mb', 'gb', 'tb'],
        i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))),
        size = bytes / Math.pow(1024, i);
    return (Math.round(size * 100) / 100) + ' ' + sizes[i];
  };

  function downloadLink(url,fileName,linkContent) {
    var link = document.createElement('a');
    link.setAttribute('href',url);
    link.setAttribute('target','_blank');

    if ( fileName ) {
      link.setAttribute('download',fileName);
    }

    if ( !linkContent ) {
      linkContent = document.createElement('img');
      linkContent.src = url;
      linkContent.setAttribute('alt',fileName);
    }

    if ( linkContent.nodeName ) {
      link.appendChild(linkContent);
    } else {
      link.innerHTML = linkContent;
    }

    return link;
  }

  function showOutput(output) {

    var fileName = this.fileName || 'jpng',
        blob = new Blob([output], {type: 'image/svg+xml'}),//output,
        blobUrl = URL.createObjectURL(blob),
        figure = document.createElement('figure'),
        figCaption = document.createElement('figcaption');

    figure.className = 'output';
    figure.appendChild(downloadLink(blobUrl,fileName+'.svg'));

    figCaption.className = 'output__details';

    figCaption.innerHTML = '<em class="output__size">Output size: ' + fileSize(output.size ? output.size : output) + '</em>';
    figCaption.appendChild( downloadLink(blobUrl,fileName+'.svg','<span class="download">Download SVG</span>') );

    var showRaw = document.createElement('button'),
        raw = document.createElement('div'),
        rawVisible = false;

    showRaw.className = 'output__show-raw';
    showRaw.innerText = "Show SVG Output";

    showRaw.addEventListener('click',function(){
      rawVisible = !rawVisible;
      showRaw.innerText = ( rawVisible ? 'Hide SVG Output' : 'Show SVG Output' );

      raw.innerHTML = ( rawVisible ? '<pre contentEditable="true" class="output__raw">' + 
                       output.replace(/</g,'&lt;').replace(/>/g,'&gt;') + 
                       '</pre>' : '' );
    });

    figCaption.appendChild(showRaw);
    
    figCaption.appendChild( downloadLink(this.options.mask.dataURL,fileName+'_mask.' + this.options.mask.type,'<span class="download">Download Mask</span>') );
    figCaption.appendChild( downloadLink(this.options.matte.dataURL,fileName+'_image.jpg','<span class="download">Download Matted Image</span>') );

    var removeOutput = document.createElement('button');
    removeOutput.className = 'output__remove';
    removeOutput.innerText = "Remove";

    removeOutput.addEventListener('click',function(){
      figure.remove();
    });
    figCaption.appendChild(removeOutput);
    figCaption.appendChild(raw);

    figure.appendChild(figCaption);
    outputDiv.insertBefore(figure,outputDiv.childNodes[0]);
  }

  window.showOutput = showOutput;
}());


////////////////////////////////////////

// CONVERT FILE

(function(){
/* 
  function Options() { return this; }
 
  Options.prototype = {
    get: function(key){ 
      return key && key !== 'get' && key !== 'set' ? this[key] : this;
    },
    set(key,value) {
      if ( value === undefined ) {
        if ( Array.isArray(key) ) {
          value = key[1];
          key = key[0];
        }
      }
      this[key] = value;
      return this;
    }
  }
  
  var opt = new Options();
  console.log(opt,opt.set('test','true'),opt.get('test'),opt.test,opt.set(['foo','bar']));
  
  function get(key) {
      return ( key ? options[key] : options ) || false;
    };
  function set(key,value) {
      console.log(key,value);
      if ( value === undefined ) {
        value = key[1];
        key = key[0];
      }
      options[key] = value;
      return this;
    };
/*    
  var options = this._options = {};
  
  Object.defineProperty(this, 'options', {
    writeable: true,
    get: get,
    set: set
  });
  
  options.get = get;
  options.set = set;
  
  console.log(this.options);
  console.log(this.options = ['test',true],this.options, this.options.test);
  console.log(this.options = ['foo','another value'],this.options, this.options.test);

*/

  function SvggyImage(file,onready){
    this.onready = onready;
    if ( file instanceof File ) {
      var name = file.name;

      this.file = file;
      this.fileName = name.slice(0,name.lastIndexOf('.')) || name + "";

      var reader = new FileReader();
      reader.onload = this.onloadFile.bind(this);
      reader.readAsDataURL(file);
    } else if ( file instanceof Node ) {
      this.convertImage(file);
    }
    console.log('SvvgyImage',this);
    return this;
  }

  var fn = SvggyImage.prototype = {};
  
  fn.onloadFile = function(src){
    var img = new Image();
    img.onload = this.convertImage.bind(this,img);
    img.src = ( src.target ? src.target.result : src );
  }

  fn.convertImage = function(img){
    img = (img.type ? this : img ); // use `this` if `img` is event
    if ( !img || img === window ) { return false; }

    this.img = img;

    this.canvas = document.createElement("canvas");
    this.width = this.canvas.width = img.naturalWidth || img.width;
    this.height = this.canvas.height = img.naturalHeight || img.height;

    var ctx = this.canvas.getContext("2d");
    ctx.drawImage(img,0,0);

    this.imageData = ctx.getImageData(0,0,this.width,this.height);   

    if ( this.onready ) { 
      this.onready.call(this);
      this.onready = false;
    }
  }

  fn.getSafeData = function(options){    
    return {
      imageData: this.imageData,
      fileName: this.fileName,
      width: this.width,
      height: this.height,
      options: options
    };
  };


  fn.process = function(process,options,callback){

    options = options || this.options;

    var safeData = this.getSafeData(options);

    var processEnd = function(processed){
      this.processed = processed;
      if ( callback ) { callback.call(this,processed); }
      console.timeEnd('conversion');
    }.bind(this);

    if ( !Modernizr.webworkers || !Modernizr.blobworkers ) {
      console.log('No workers or blog support. Larger images may timeout.');
      processEnd(process(safeData));
    } else {
      var imageWorker = cw(process);
      imageWorker.data(safeData).then(processEnd,function(e){ 
        console.error(e);
        console.timeEnd('conversion');
      });
    }
  }

  window.SvggyImage = SvggyImage;

}());

(function(){
  /*

    function each(obj,fn) {
      var length = obj.length,
          likeArray = ( length === 0 || ( length > 0 && (length - 1) in obj ) ),
          i = 0;

      if ( likeArray ) {
        for ( ; i < length; i++ ) { if ( fn.call( obj[ i ], i, obj[ i ] ) === false ) { break; } }
      } else {
        for (i in obj) { if ( fn.call( obj[ i ], i, obj[ i ] ) === false ) { break; } }
      }
    }

    function componentToHex(c) {
      var hex = parseInt(c).toString(16);
      return hex.length == 1 ? "0" + hex : hex;
    }

    function getColor(r,g,b,a){
      a = parseInt(a);
      if ( a === undefined || a === 255 ) { return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b); }
      if ( a === 0 ) { return false; }
      return 'rgba('+r+','+g+','+b+','+(a/255)+')';
    }

    // Optimized for horizontal lines
    function makePathData(x,y,w) { return ('M'+x+' '+y+'h'+w+''); }
    function makePath(color,data) { return '<path stroke="'+color+'" d="'+data+'" />\n'; }

    function alphasToPaths(colors){

      var output = ""; 

      // Loop through each color to build paths
      each(colors,function(color,values){
        var orig = color;
        color = 'rgba(0,0,0,'+(255-color)+')';

        if ( color === false ) { return; }

        var paths = [];
        var curPath;
        var w = 1;

        // Loops through each color's pixels to optimize paths
        each(values,function(){

          if ( curPath && this[1] === curPath[1] && this[0] === (curPath[0] + w) ) {
            w++;
          } else {
            if ( curPath ) {
              paths.push(makePathData(curPath[0],curPath[1],w));
              w = 1;
            }
            curPath = this;
          }

        });

        paths.push(makePathData(curPath[0],curPath[1],w)); // Finish last path
        output += makePath(color,paths.join(''));
      });

      return output;
    }

    var getAlphas = function(img) {
      var alphas = {},
          data = img.data,
          len = data.length,
          w = img.width,
          h = img.height,
          x = 0,
          y = 0,
          i = 0,
          alpha;      

      for (; i < len; i+= 4) {
        if ( data[i] < 255 ) {
          alpha = data[i];// - (data[i] + data[i+1] + data[i+2])/3;
          //alpha = alpha.toFixed(2);

          x = (i / 4) % w;
          y = Math.floor((i / 4) / w);

          alphas[alpha] = alphas[alpha] || [];
          alphas[alpha].push([x,y]);
        }                      
      }

      return alphas;
    }

    function makeMask(paths,imgData){

      var mask = imgData.mask,
          img = imgData.imageData;

      //return '<defs><mask id="a"><image width="'+img.width+'" height="'+img.height+'" xlink:href="'+mask.dataURL+'"/></mask></defs>';

      return '<defs><mask id="a"><rect width="100%" height="100%" fill="white" />' + paths + '</mask></defs>';
    }/**/

}());
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console