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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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

              
                <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="600" height="600" viewBox="0 0 600 600">
  <defs>
    <linearGradient id="grad" x1="0%" y1="100%" x2="10%" y2="0%">
      <stop offset="0%" style="stop-color:rgb(255,255,255);stop-opacity:0.2" />
      <stop offset="100%" style="stop-color:rgb(255,255,255);stop-opacity:0.1" />
    </linearGradient>
  </defs>
  <rect x="0" y="0" width="600" height="600" fill="rgb(252,68,63)" />
  <!--  filter="url(#goo)" -->
  <g id="content">
  </g>
</svg>

<div id="controls">
  <div class="row">
    <button id="exportpng">Export PNG</button> <button id="exportsvg">Export SVG</button>
  </div>
  <div class="row">
    <input type="checkbox" checked name="autoplay" id="autoplay" /> <label for="autoplay">Autoplay</label>
  </div>
</div>

              
            
!

CSS

              
                body {
  width: 100vw; height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #000;
  margin: 0;
  padding: 0;
  color: #999;
  font-family: sans-serif;
}
#controls {
  padding: 20px;
}
.row {
  margin-bottom: 10px;
  text-align: center;
}
.container {
  display: flex;
  flex-direction: column;
  filter: url(#goo);
}
              
            
!

JS

              
                const ns = 'http://www.w3.org/2000/svg';

const svg = document.querySelector('svg');
const content = svg.getElementById('content');

const element = (type, attrs) => {
  const el = document.createElementNS(ns, type);
  for (let key in attrs) {
    el.setAttribute(key, attrs[key]);
  }
  return el;
};

const rand = (a, b) =>
  Math.random()*(b-a) + a;

const add = (a, b) => a.map((v,i) => v+b[i]);
const scale = (a, k) => a.map(v => v*k);
const sub = (a, b) => add(a, scale(b, -1));
const dist = (a, b) => Math.hypot(...add(a, scale(b, -1)));
const lerp = (a, b, t) => a.map((v,i) => v*(1-t) + b[i]*t);

const hslToRgb = (h, s, l) => {
  let r, g, b;

  if (s == 0) {
    r = g = b = l; // achromatic
  } else {
    const hue2rgb = (p, q, t) => {
      if (t < 0) t += 1;
      if (t > 1) t -= 1;
      if (t < 1/6) return p + (q - p) * 6 * t;
      if (t < 1/2) return q;
      if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
      return p;
    };

    var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
    var p = 2 * l - q;
    r = hue2rgb(p, q, h + 1/3);
    g = hue2rgb(p, q, h);
    b = hue2rgb(p, q, h - 1/3);
  }

  return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
};

const d = (instructions) =>
  instructions.map(([type, ...pts]) => type + pts.map(pt => ` ${pt[0].toFixed(4)} ${pt[1].toFixed(4)}`).join('')).join(' ');

const append = (el) => content.appendChild(el);

const clear = () => {
  while (content.firstChild) {
    content.removeChild(content.firstChild);
  }
};

const generate = () => {
  clear();
  
  const contours = [
    [[100, 100], [500, 100], [500, 500], [100, 500]]
  ];
  
  const totalLength = contour => {
    let total = 0;
    for (let i = 0; i < contour.length; i++) {
      total += dist(contour[(i+1)%contour.length], contour[i]);
    }
    return total;
  };
  const pointAtLength = (contour, len) => {
    let lenSoFar = 0;
    let idx = 0;
    for (let i = 0; ; i = (i+1)%contour.length) {
      const nextLen = dist(contour[i], contour[(i+1)%contour.length]);
      if (lenSoFar + nextLen > len) {
        idx = i + (lenSoFar + nextLen - len)/nextLen;
        break;
      } else {
        lenSoFar += nextLen;
      }
    }
    
    pt = lerp(
      contour[Math.floor(idx)],
      contour[Math.ceil(idx) % contour.length],
      idx - Math.floor(idx));
    return [pt, idx];
  };
  
  const split = pts => {
    const sideLengths = pts.map((pt,i) => dist(pt, pts[(i+1)%pts.length]));
    const sideIndices = pts.map((_,i) => i).sort((a,b) => sideLengths[b]-sideLengths[a]);
    const id1 = rand(sideIndices[0], sideIndices[0]+1);
    //const id2 = rand(sideIndices[1], sideIndices[1]+1);
    const id2 = (Math.floor(id1) + 2 + (1 - (id1 - Math.floor(id1))) + rand(-0.2, 0.2)) % pts.length;
    const pt1 = lerp(
      pts[Math.floor(id1)],
      pts[Math.ceil(id1)%pts.length],
      id1 - Math.floor(id1));
    const pt2 = lerp(
      pts[Math.floor(id2)],
      pts[Math.ceil(id2)%pts.length],
      id2 - Math.floor(id2));
    //const total = totalLength(pts);
    //const [pt1, id1] = pointAtLength(pts, rand(0, total));
    //const [pt2, id2] = pointAtLength(pts, rand(0, total));
    
    const side1 = [pt1.slice()];
    for (
        let i = Math.ceil(id1)%pts.length;
        !(i < id2 && i+1 >= id2);
        i = (i+1)%pts.length) {
      side1.push(pts[i].slice());
    }
    side1.push(pts[Math.floor(id2)].slice());
    side1.push(pt2.slice());
    const side2 = [pt2.slice()];
    for (
        let i = Math.ceil(id2)%pts.length;
        !(i < id1 && i+1 >= id1);
        i = (i+1)%pts.length) {
      side2.push(pts[i].slice());
    }
    side2.push(pts[Math.floor(id1)].slice());
    side2.push(pt1.slice());
    
    return [side1, side2];
  };
  
  for (let n = 0; n < 20; n++) {
    const toSplit = Math.floor(rand(0, contours.length));
    let side1 = [];
    let side2 = [];
    while (side1.length < 3 || side2.length < 3) {
      [side1, side2] = split(contours[toSplit]);
    }
    contours.splice(toSplit, 1, side1, side2);
  }
  
  contours.forEach(pts => {
    const [cx, cy] = scale(pts.reduce((sum, next) => add(sum, next), [0, 0]), 1/pts.length);
    
    let area = 0
    let p0 = pts[0];
    pts.slice(1).forEach(p1 => {
      const [dx, dy] = sub(p1, p0);
      const [x0, y0] = p0;
      area += 0.5*(y0*dx - x0*dy);
      p0 = p1;
    });
    
    const a = 20000 * rand(-1, 1) / area;
    const offX = 10000 * rand(-1, 1) / area;
    const offY = 10000 * rand(-1, 1) / area;
    
    const pane = element(
      'g',
      {
        transform: `rotate(${a} ${cx.toFixed(4)} ${cy.toFixed(4)}) ` +
        `translate(${offX.toFixed(4)} ${offY.toFixed(4)})`,
      }
    );
    const shape = element(
      'path',
      {
        d: d([
          ['M', pts[0]],
          ...pts.slice(1).map(pt => ['L', pt]),
          ['Z']
        ]),
        stroke: 'rgb(252,68,63)',
        'stroke-width': 1,
        'stroke-linecap': 'round',
        fill: '#FFF'
      }
    );
    pane.appendChild(shape);
    append(pane);
  });
};

generate();

const autoplay = document.getElementById('autoplay');
setInterval(() => {
  if (autoplay.checked) generate();
}, 2000);
svg.addEventListener('click', generate);

document.getElementById('exportpng').addEventListener('click', () => {
  const filename = "shatter.png";
  const scale = 4;
  const serializer = new XMLSerializer();
  const canvas = document.createElement('canvas');
  canvas.setAttribute('width', 600 * scale);
  canvas.setAttribute('height', 600 * scale);

  const exportSvg = svg.cloneNode(true);
  exportSvg.setAttribute('width', 600 * scale);
  exportSvg.setAttribute('height', 600 * scale);
  exportSvg.setAttribute('style', `width: ${600*scale}px; height: ${600*scale}px;`);

  const ctx = canvas.getContext('2d');
  const img = new Image();
  img.onload = () => {
    ctx.drawImage(img, 0, 0);
    canvas.toBlob((pngBlob) => {
      const downloader = document.createElement('a');
      downloader.setAttribute('href', URL.createObjectURL(pngBlob));
      downloader.setAttribute('download', filename);
      document.body.appendChild(downloader);
      downloader.click();
      console.log('clicked');
      document.body.removeChild(downloader);
    }, 'image/png');
  };
  img.onerror = (e) => {
    throw e;
  };

  img.src = 'data:image/svg+xml;utf8,' + encodeURIComponent(serializer.serializeToString(exportSvg));
});

document.getElementById('exportsvg').addEventListener('click', () => {
  const filename = "shatter.svg";
  const serializer = new XMLSerializer();
  const src = serializer.serializeToString(svg);
  const blob = new Blob([src], { type: 'text/plain;charset=utf-8' });
  const downloader = document.createElement('a');
  downloader.setAttribute('href', URL.createObjectURL(blob));
  downloader.setAttribute('download', filename);
  document.body.appendChild(downloader);
  setTimeout(() => {
    downloader.click();
    document.body.removeChild(downloader);
  }, 0);
});
              
            
!
999px

Console