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

              
                <h1>Cloudinary SVG Placeholder</h1>

<div class="column">
  <p>Dynamic SVG image placeholders, powered by <a href="https://cloudinary.com/">Cloudinary</a> & <a href="https://github.com/kilobtye/potrace">Potrace</a></p>
  <p class="center">
    <label><span class="double"><input type="checkbox" name="stroke" checked=checked /></span> Animated Outline</label>
  </p>
</div>

<cloudinary-svg-placeholder
  src="https://images.unsplash.com/photo-1529933037705-0d537317ae7b"
  alt="Hello world"
  color="lightgray"
  width=500
  cloudinary="demo"
  animated-stroke=true
></cloudinary-svg-placeholder>

<div class="column">
  <p><small><center>(Image from <a href="https://unsplash.com/">unsplash.com</a>)</small></center></p>
  <p>Try these images:</p>
  <p><ul>
    <li><a class="alternateImg" href="https://images.unsplash.com/photo-1529932702015-d79f7e363168">Camera</a></li>
    <li><a class="alternateImg" href="https://images.unsplash.com/photo-1529933037705-0d537317ae7b">Surprised Cat</a></li>
    <li><a class="alternateImg" href="https://images.unsplash.com/photo-1529840180348-efd52969a4ce">Mountains</a></li>
  </ul></p>
  <h2>How it works</h2>
  <p><ol>
    <li>Loads the <a href="https://github.com/kilobtye/potrace">Potrace Lib</a> (6KB min+gzip)</li>
    <li>Starts loading the full res source image</li>
    <li>Meanwhile...</li>
    <li><ol>
      <li>Grabs a <a href="https://res.cloudinary.com/demo/image/fetch/q_10,f_jpg,w_150/https://images.unsplash.com/photo-1529933037705-0d537317ae7b">low res thumbnail from Cloudinary</a> (~5KB)</li>
      <li>Uses Potrace to generate an svg from the thumbnail</li>
      <li>Colours and fades the SVG in as a crisp, full-size placeholder</li>
    </ol></li>
    <li>Once full res loaded, overlays the svg with a nice fadein transition</li>
  </ol></p>
  <h2>FAQs</h2>
  <p><ul>
    <li>๐Ÿšซ No build step required!</li>
    <li>๐Ÿฆ‰ The SVG is generated on the fly from the source image</li>
    <li>๐ŸŽ’ It requires an extra network round trip (to fetch the thumb from Cloudinary)</li>
    <li>๐ŸŒˆ You can pick any colour for the svg</li>
    <li>๐Ÿ’… The SVG can be animated / styled however you want</li>
  </ul></p>
  <p><i>Note: This demo artificially delays image loading by 1 second</i></p>
  <hr />
  <p>Created by <a href="https://mobile.twitter.com/jesstelford">@jesstelford</a></p>
</div>
              
            
!

CSS

              
                :root {
  font-family: Menlo, monospace;
  font-size: calc( 0.8em + 1vmin );
}

cloudinary-svg-placeholder {
  min-height: 504px;
}

img, cloudinary-svg-placeholder {
  display: block;
  margin: 0 auto;
}

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

.column {
  max-width: 20em;
  margin: 0 auto;
}

.column a {
  cursor: pointer;
  color: inherit;
}

.column a:hover {
  text-decoration: underline;
}

.double {
  zoom: 2;
  transform: scale(2);
  -ms-transform: scale(2);
  -webkit-transform: scale(2);
  -o-transform: scale(2);
  -moz-transform: scale(2);
  transform-origin: 0 0;
  -ms-transform-origin: 0 0;
  -webkit-transform-origin: 0 0;
  -o-transform-origin: 0 0;
  -moz-transform-origin: 0 0;
  -webkit-transform-origin: 0 0;
}
              
            
!

JS

              
                const ARTIFICIAL_DELAY = 2000;

function createElementFromHTML(htmlString) {
  const div = document.createElement('div');
  div.innerHTML = htmlString;
  return div.firstChild; 
}

class CloudinaryImg extends HTMLElement {
  static get observedAttributes() {
    return ['animated-stroke', 'src'];
  }
	constructor() {
		super();
    this.lowResWidth = 150;
		this.cloudName = this.getAttribute('cloudinary');
    this.state = {
      animatedStroke: this.getAttribute('animated-stroke'),
      src: this.getAttribute('src'),
    };
    this.attachShadow({mode: 'open'});
    this.initialise();
    this.render();
	}
  
  initialise() {
    this.imageLoaded = false;
    this.svg = undefined;
    this.svgElement = undefined;
    this.width = this.getAttribute('width') || this.lowResWidth;
    this.height = this.getAttribute('height') || this.lowResWidth;
    
    this.shadowRoot.innerHTML = `
        <style>
          :host {
             width: ${this.width}px;
          }
          svg {
            display: block;
            margin: 0 auto;
            left: 0;
            right: 0;
          }
          .background {
            position: absolute;
            z-index: -1;
          }
          .hidden {
            opacity: 0;
            transition: opacity 0.3s ease-in;
          }
          .fade-in {
            opacity: 1;
          }
          .animate-dash {
            stroke-dasharray: var(--path-length);
            stroke-dashoffset: var(--path-length);
            animation: dash 5s linear forwards;
          }

          @keyframes dash {
            to {
              stroke-dashoffset: 0;
            }
          }
        </style>
      `;
  }
  
  render() {
    this.traceImage(
      `https://res.cloudinary.com/${this.cloudName}/image/fetch/q_10,f_jpg,w_${this.lowResWidth}/${this.state.src}`,
      (svg) => {
        this.svg = svg;
        this.showSVGWhenConnected();
      }
    );
    
    this.loadFullImage(() => {
      this.imageLoaded = true;
      this.showFullImageWhenLoaded();
    });
  }
  
  // Only called for the disabled and open attributes due to observedAttributes
  attributeChangedCallback(name, oldValue, newValue) {
    if (['src', 'animated-stroke'].indexOf(name) !== -1 && oldValue !== newValue) {
      if (name === 'animated-stroke') {
        name = 'animatedStroke';
      }
      this.state[name] = newValue;
      this.initialise();
      this.render();
    }
  }
  
  traceImage(url, callback) {
    // Enable CORS support
    window.Potrace.img.crossOrigin = 'Anonymous';
    window.Potrace.loadImageFromUrl(url);
    window.Potrace.process(() => {
      callback(window.Potrace.getSVG(this.width / this.lowResWidth, this.state.animatedStroke ? "curve" : undefined));
    });
  }
  
  loadFullImage(done) {
    this.fullImage = createElementFromHTML(`<img alt="${this.getAttribute('alt') || ''}" width=${this.width} />`)
    this.fullImage.onload = () => {
      done();
    };
    
    // artificial delay for fast networks
    window.setTimeout(() => {
      this.fullImage.src = this.state.src;
    }, ARTIFICIAL_DELAY); 
  }
  
  showSVGWhenConnected() {
    // Only proceed if we're mounted in the DOM, the svg is loaded, and we haven't already shown the image
    if (!this.connected || !this.svg || this.imageLoaded) {
      return;
    }
    this.svgElement = createElementFromHTML(this.svg);
    this.svgElement.classList.add('hidden');
    // Firefox hack to get the fadein animation to work
    window.requestAnimationFrame(() => {
      window.requestAnimationFrame(() => {
        this.svgElement.classList.add('fade-in');
      })
    })
    const pathEl = this.svgElement.querySelector('path');
    if (this.state.animatedStroke) {
      pathEl.setAttribute('stroke-width', this.getAttribute('stroke-width') || '3');
      pathEl.setAttribute('stroke', this.getAttribute('color') || 'gray');
      pathEl.classList.add('animate-dash');
      const pathLength = Math.ceil(pathEl.getTotalLength());
      pathEl.style.setProperty('--path-length', pathLength);
    } else {
      pathEl.setAttribute('fill', this.getAttribute('color') || 'gray');
    }
    this.shadowRoot.appendChild(this.svgElement);
  }
  
  showFullImageWhenLoaded() {
    // Only proceed if we're mounted in the DOM, and the image is loaded
    if (!this.connected || !this.imageLoaded) {
      return;
    }
    if (this.svgElement) {
      this.svgElement.classList.add('background');
    }
    this.fullImage.classList.add('hidden');
    this.shadowRoot.appendChild(this.fullImage);
    // Firefox hack to get the fadein animation to work
    window.requestAnimationFrame(() => {
      window.requestAnimationFrame(() => {
        this.fullImage.classList.add('fade-in');
      })
    })
  }
  
	connectedCallback() {
    this.connected = true;
    this.showSVGWhenConnected();
    this.showFullImageWhenLoaded();
	}
}

customElements.define('cloudinary-svg-placeholder', CloudinaryImg);

const imgEL = document.querySelector('cloudinary-svg-placeholder');

document.querySelectorAll('a.alternateImg').forEach((node) => {
  node.addEventListener('click', (event) => {
    event.preventDefault();
    event.stopPropagation();
    imgEL.setAttribute('src', event.target.getAttribute('href'));
  })
})

document.querySelector('input[name="stroke"]').addEventListener('change', (event) => {
  if (event.target.checked) {
    imgEL.setAttribute('animated-stroke', true);
  } else {
    imgEL.removeAttribute('animated-stroke');
  }
})
              
            
!
999px

Console