Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs 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 its URL and the proper URL extension.

+ 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

Auto Save

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

              
                <p class="info">
  Drag the handles to change the displacment map on the left. See it
  how it will affect the distortion of the image on the right.
</p>
<div class="wrapper" id="fe-filter-demo-wrapper">
  <section class="wrapper__svg-container">
    <svg id='feimage-input' class="wrapper__displacement-svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" preserveAspectRatio="none" version="1.1" viewBox="0 0 256 256">
      <defs>
        <style type="text/css">
          .red-blur {
            fill: transparent;
            stroke: #ff0000;
            stroke-width: 256px;
          }

          .blue-blur {
            fill: transparent;
            stroke: #0000ff;
            stroke-width: 256px;
            mix-blend-mode: screen;
          }
        </style>

        <filter id="feimginput__blur" width="512" height="512" x="-128" y="-128" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse" primitiveUnits="userSpaceOnUse">
          <feGaussianBlur in="SourceGraphic" stdDeviation="64" />
          <feComponentTransfer>
            <feFuncA type="table" tableValues="0 .195 .31 .37 .43 .5 .58 .65 .72 .83 1.0" />
          </feComponentTransfer>
        </filter>

        <mask id="clip">
          <rect width="256" height="256" x="0" y="0" fill="#fff"></rect>
        </mask>
      </defs>
      <g class="feimage-input__absolutemap" mask="url(#clip)">
        <rect width="256" height="256" x="0" y="0" fill="#000"></rect>
        <g filter="url(#feimginput__blur)">
          <path d="" class="red-blur red-path"></path>
          <path d="" class="blue-blur blue-path"></path>
        </g>
      </g>
    </svg>
    <svg id='demo-curves' class="wrapper__demo-curves-svg" width="100%" height="100%" preserveAspectRatio="none" version="1.1" viewBox="0 0 256 256">
      <defs>
        <style type="text/css">
          .red-curve {
            fill: transparent;
            stroke: #FFAAAA;
            stroke-width: 1px;
          }

          .blue-curve {
            fill: transparent;
            stroke: #96D2FF;
            stroke-width: 1px;
          }
        </style>
      </defs>
      <g>
        <path id="red-demo-curve" d="" class="red-curve red-path"></path>
        <path id="blue-demo-curve" d="" class="blue-curve blue-path"></path>
      </g>
    </svg>
  </section>
  <svg id="filteredSVG" class="wrapper__filtered" width="256" height="256" preserveAspectRatio="none" version="1.1" viewBox="0 0 256 256">
    <defs>
      <filter id="filter" width="256" height="256" x="0" y="0" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse">
        <feImage id="feimg" width="100%" height="100%" x="0" y="0" result="FEIMG" xlink:href="#feimage-input" />
        <feDisplacementMap id="fedisplacementmap" in="SourceGraphic" in2="FEIMG" scale="100" xChannelSelector="R" yChannelSelector="B" />
      </filter>
    </defs>
    <image href="https://assets.codepen.io/100347/fedm_azrael.jpg" image-rendering="high-quality" id="filteredSVG__img" x="0" y="0" height="256px" width="256px" filter="url(#filter)" />
  </svg>
  <section class="wrapper__thumbs">
    <img class="wrapper__thumb" src="https://assets.codepen.io/100347/fed_monalisa-384.jpg" />
    <img class="wrapper__thumb" src="https://assets.codepen.io/100347/fedm_brucelee.svg" />
    <img class="wrapper__thumb" src="https://assets.codepen.io/100347/fedm_gradient.svg" />
    <img class="wrapper__thumb" src="https://assets.codepen.io/100347/fedm_azrael.jpg" />
    <img class="wrapper__thumb" src="https://assets.codepen.io/100347/fedm_disney.jpg" />
    <img class="wrapper__thumb" src="https://assets.codepen.io/100347/fedm_orange.jpg" />
    <img class="wrapper__thumb" src="https://assets.codepen.io/100347/fedm_pattern-a.svg" />
  </section>
  <input class="wrapper__scale-range" id="scale" type="range" min="-256" max="256" steps="4" value="70" size="50" />
</div>
              
            
!

CSS

              
                @use postcss-preset-env;
@custom-media --bp-md (width >=760px);

*,
*::before,
*::after {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

html {
    height: 100%;
}

body {
    margin: 0;
    padding: 1.25em;
    height: 100%;
    color: white;
    font: 0.85em -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
    min-width: 320px;
    background: radial-gradient(circle, rgba(2, 63, 87, 1) 0%, #000 71%);
    display: flex;
    flex-direction: column;
}

p {
    margin-bottom: 1em;
}

.filter {
    position: absolute;
    top: 0;
    left: -1;
    width: 1px;
    height: 1px;
    visibility: hidden;
}

.block-scroll {
    touch-action: none;
    overflow: hidden;
}

.info {
    text-align: center;
    color: white;
    margin: 0 auto;
    padding: 0.5em;
    max-width: 40em;
    flex: 0 0 auto;
}

.wrapper {
    display: block;
    position: relative;
    width: 512px;
    height: 360px;
    margin: auto;
    flex: 0 0 auto;
}

.wrapper__svg-container {
    position: absolute;
    left: 0;
    top: 0;
    width: 256px;
    height: 256px;
    pointer-events: none;
}

.wrapper__displacement-svg {
    z-index: 1000;
    transform-origin: 0 0;
}

.wrapper__demo-curves-svg {
    z-index: 3000;
}

.wrapper__displacement-svg,
.wrapper__demo-curves-svg {
    position: absolute;
    top: 0;
    left: 0;
    width: 256px;
    height: 256px;
    overflow: visible;
}

.wrapper__filtered {
    position: absolute;
    left: 256px;
    top: 0;
    width: 256px;
    height: 256px;
}

.wrapper__thumbs {
    position: absolute;
    z-index: 2000;
    bottom: 30px;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    align-items: stretch;
}

.wrapper__thumb {
    display: inline-block;
    width: 64px;
    height: 64px;
    flex: 0 0 64px;
    transition: transform 0.2s;
    cursor: pointer;

    &:hover {
        transform: scale(1.1, 1.1);
    }
}

.bezpoint,
.bezpoint-red-start,
.bezpoint-red-end,
.bezpoint-blue-start,
.bezpoint-blue-end {
    display: block;
    position: absolute;
    padding: 0;
    appearance: none;
    border: solid white 1px;
    width: 22px;
    height: 22px;
    cursor: pointer;
    overflow: hidden;
    z-index: 200000;
    left: 50%;
    top: 50%;
    transform: translate(-40%, -40%);
    outline: none;

    @media (--bp-md) {
        width: 14px;
        height: 14px;
    }
}

.bezpoint-red-start,
.bezpoint-red-end {
    background: #ff0000;
}

.bezpoint-blue-start,
.bezpoint-blue-end {
    background: #0000ff;
    transform: translate(-60%, -60%);
}

.bezpoint-blue-end,
.bezpoint-red-end {
    border-radius: 50%;
}

.wrapper__scale-range {
    position: absolute;
    z-index: 2000;
    bottom: 0;
    left: 0;
    right: 0;
}

input[type='range'] {
    appearance: none;
    display: block;
    background-color: rgba(255, 255, 255, 0.85);
    margin: 10px 0 0;
    width: 512px;

    &:focus {
        outline: none;
    }

    &::-webkit-slider-thumb {
        appearance: none;
        background-color: white;
        width: 30px;
        height: 20px;
        cursor: pointer;
    }

    &::-moz-range-track {
        background-color: white;
        border: none;
        margin: 0;
        padding: 0;
        outline: 0;
    }

    &::-moz-range-thumb {
        background-color: white;
        width: 30px;
        height: 20px;
        cursor: pointer;
        border: none;
        border-radius: 0;
        margin: 0;
    }

    &::-ms-fill-lower {
        background: #ff3632;
    }

    &::-ms-fill-upper {
        background: #ffaa00;
    }

    &::-ms-thumb {
        background: white;
    }

    &::-ms-ticks-after {
        display: none;
        color: blue;
    }

    &::-ms-ticks-before {
        display: none;
        color: black;
    }

    &::-ms-track {
        padding: 0;
        cursor: pointer;
    }

    &::-ms-tooltip {
        display: none;
    }
}

              
            
!

JS

              
                const filteredPic = document.querySelector("#filteredSVG__img");
const feDisplacementMap = document.querySelector("#fedisplacementmap");
const demoCurves = document.querySelector("#demo-curves");
const slider = document.querySelector("#scale");
const demoEl = document.getElementById("fe-filter-demo-wrapper");
const thumbs = document.querySelectorAll(".wrapper__thumb");
let redPathElems;
let bluePathElems;

class BezBtn {
  container;
  b;
  hContainer;
  svg;
  svgOffset;
  svgNS;
  screenPt_start;
  screenPt_end;
  svgPt_start;
  svgPt_end;
  screenCoordsStart;
  screenCoordsEnd;
  startButton;
  endButton;
  callback;
  line;
  maxZ = 20000;

  constructor(
    svg,
    cName,
    startPoint,
    endPoint,
    containerElem = document.body,
    callback
  ) {
    this.svg = svg;
    this.b = document.body;
    this.container = containerElem;
    const rect = this.svg.getBoundingClientRect();
    this.svgOffset = [rect.left, rect.top];
    this.svgNS = this.svg.getAttribute("xmlns");
    this.svgPt_start = this.svg.createSVGPoint();
    this.svgPt_end = this.svg.createSVGPoint();
    this.screenPt_start = this.svg.createSVGPoint();
    this.screenPt_end = this.svg.createSVGPoint();
    this.screenCoordsStart = this.svg2Screen(...startPoint, "start");
    this.screenCoordsEnd = this.svg2Screen(...endPoint, "end");
    this.svgPt_start.x = startPoint[0];
    this.svgPt_start.y = startPoint[1];
    this.svgPt_end.x = endPoint[0];
    this.svgPt_end.y = endPoint[1];
    this.svgPt_start.matrixTransform(this.svg.getScreenCTM().inverse());
    this.svgPt_end.matrixTransform(this.svg.getScreenCTM().inverse());

    this.createButton(`${cName}-start`, this.screenCoordsStart, "start");
    this.createButton(`${cName}-end`, this.screenCoordsEnd, "end");
    this.createHandle(startPoint);
    this.moveBez = this.moveBez.bind(this);
    this.stopMoveBez = this.stopMoveBez.bind(this);
    this.preventScroll = this.preventScroll.bind(this);
    this.restoreScroll = this.restoreScroll.bind(this);

    if (callback) {
      this.callback = callback;
    }
  }

  createButton(cName, coords, type) {
    const btnName = `${type}Button`;
    this[btnName] = document.createElement("button");
    this[btnName].classList.add(cName);
    this[btnName].style.left = `${coords[0]}px`;
    this[btnName].style.top = `${coords[1]}px`;
    this[btnName].style.zIndex = this.maxZ;
    this[btnName].dataset.type = type;
    this.container.appendChild(this[btnName]);
    this[btnName].addEventListener("pointerdown", this.initMove);
  }

  updateHandle(x, y) {
    const num = this.currentType === "start" ? 1 : 2;
    this.line.setAttribute(`x${num}`, x);
    this.line.setAttribute(`y${num}`, y);
  }

  createHandle(sp) {
    this.hContainer = document.createElementNS(
      "http://www.w3.org/2000/svg",
      "svg"
    );
    this.hContainer.setAttribute("width", "50%");
    this.hContainer.setAttribute("height", "100%");
    this.hContainer.setAttribute(
      "style",
      `overflow:visible;position:absolute;top:0px; left:0px;z-index: 3000;pointer-events: none;`
    );
    this.line = document.createElementNS("http://www.w3.org/2000/svg", "line");
    this.line.setAttribute("x1", Math.floor(sp[0]));
    this.line.setAttribute("y1", Math.floor(sp[1]));
    this.line.setAttribute("x2", Math.floor(this.screenCoordsEnd[0]));
    this.line.setAttribute("y2", Math.floor(this.screenCoordsEnd[1]));
    this.line.setAttribute("stroke", "#fff");
    this.hContainer.appendChild(this.line);
    this.container.appendChild(this.hContainer);
  }

  svg2Screen(x, y, svgPt) {
    this[`screenPt_${svgPt}`].x = x - this.svgOffset[0];
    this[`screenPt_${svgPt}`].y = y - this.svgOffset[1];
    const screenPMT = this[`screenPt_${svgPt}`].matrixTransform(
      this.svg.getScreenCTM()
    );

    return [screenPMT.x.toFixed(2), screenPMT.y.toFixed(2)];
  }

  screen2SVG(x, y, svgPt) {
    this[`svgPt_${svgPt}`].x = x - this.svgOffset[0];
    this[`svgPt_${svgPt}`].y = y - this.svgOffset[1];
    const svgPMT = this[`svgPt_${svgPt}`].matrixTransform(
      this.svg.getScreenCTM().inverse()
    );

    return [svgPMT.x, svgPMT.y];
  }

  moveBez(e) {
    e.preventDefault();
    const btn = this[`${this.currentType}Button`];
    const x = `${e.clientX - this.svgOffset[0]}px`;
    const y = `${e.clientY - this.svgOffset[1]}px`;
    btn.style.left = x;
    btn.style.top = y;
    this.updateHandle(x, y);
    this.screen2SVG(e.clientX, e.clientY, this.currentType);

    if (this.callback) {
      this.callback();
    }
  }

  stopMoveBez(e) {
    this.restoreScroll(e);
    const btn = this[`${this.currentType}Button`];
    btn.style.zIndex = this.maxZ - 10;
    this.b.removeEventListener("pointermove", this.moveBez);
    this.b.removeEventListener("pointerup", this.stopMoveBez);
    btn.addEventListener("pointerdown", this.initMove);
  }

  initMove = (e) => {
    e.preventDefault();
    this.preventScroll(e);
    const btn = e.target;

    btn.removeEventListener("pointerdown", this.initMove);
    this.b.addEventListener("pointermove", this.moveBez);
    this.b.addEventListener("pointerup", this.stopMoveBez);
    this.currentType = btn.dataset.type;
    btn.style.zIndex = this.maxZ;

    const rect = this.svg.getBoundingClientRect();
    this.svgOffset = [rect.left, rect.top];
  };

  preventScroll(e) {
    document.body.classList.add("block-scroll");

    return;
  }

  restoreScroll(e) {
    document.body.classList.remove("block-scroll");

    return;
  }
}

class PathData {
  col;
  map;
  demopath;
  path;
  uriPath;
  pathArr;
  bezHandles = [];
  sp = [];
  ep = [];
  cp = [];
  update;
  targetSVG;

  constructor(col, map, pathArr, rootEl, targetSVG, applyToFeImage) {
    if (applyToFeImage) {
      this.update = this.updateDataAtrib;
    } else {
      this.update = this.updateURI;
    }
    this.col = col;
    this.map = map;
    this.pathArr = pathArr;
    this.sp = col == "red" ? [0, -128] : [-128, 0];
    this.ep = col == "red" ? [0, 384] : [384, 0];
    this.cp =
      col == "red"
        ? [
            [0, 120],
            [0, 134]
          ]
        : [
            [120, 0],
            [134, 0]
          ];
    this.targetSVG = document.querySelector(targetSVG);

    this.bezHandles[0] = new BezBtn(
      this.targetSVG,
      `bezpoint-${col}`,
      this.sp,
      this.cp[0],
      rootEl,
      function () {
        this.update(0);
      }.bind(this)
    );
    this.bezHandles[1] = new BezBtn(
      this.targetSVG,
      `bezpoint-${col}`,
      this.ep,
      this.cp[1],
      rootEl,
      function () {
        this.update(1);
      }.bind(this)
    );
    this.update(0);
    this.update(1);
  }

  calcPathData(n) {
    this.sp = [
      this.bezHandles[0].svgPt_start.x,
      this.bezHandles[0].svgPt_start.y
    ];
    this.ep = [
      this.bezHandles[1].svgPt_start.x,
      this.bezHandles[1].svgPt_start.y
    ];
    this.cp[n] = [
      this.bezHandles[n].svgPt_end.x,
      this.bezHandles[n].svgPt_end.y
    ];
    this.path = `M${this.sp} C${this.cp[0]} ${this.cp[1]} ${this.ep}`;
    this.pathArr.forEach((path) => {
      path.setAttribute("d", this.path);
    });
  }

  updateDataAtrib(n) {
    this.calcPathData(n);
    this.map.update(this.col, this.path);
  }

  updateURI(n) {
    this.calcPathData(n);
    this.uriPath = encodeURIComponent(this.path);

    this.map.update(this.col, this.uriPath);
  }
}

class DisplacementMapUpdater {
  nsAttr = "http://www.w3.org/2000/svg";
  xlinkAttr = "http://www.w3.org/1999/xlink";
  slicedTemplateArr = [];
  feImgEl;
  feImgInputEl;
  redPathData = "";
  bluePathData = "";
  update;

  constructor(feimgQuery, applyToFeImage) {
    this.feImgEl = document.querySelector(feimgQuery);
    const feImgInputElemId =
      this.feImgEl.getAttribute("xlink:href") ||
      this.feImgEl.getAttribute("xlink");
    this.feImgInputEl = document.querySelector(feImgInputElemId);

    if (
      !this.feImgInputEl ||
      /data\:image\/svg\+xml/gi.test(feImgInputElemId) ||
      /blob\:/gi.test(feImgInputElemId)
    ) {
      return;
    }

    if (!this.feImgInputEl.getAttribute("xmlns")) {
      this.feImgInputEl.setAttribute("xmlns", this.nsAttr);
    }

    if (applyToFeImage) {
      this.redblur = this.feImgInputEl.querySelector(".red-blur");
      this.blueblur = this.feImgInputEl.querySelector(".blue-blur");
      this.update = this.updatePath;
    } else {
      this.update = this.updateFeImageUri;
      const slicedHTMLString = this.feImgInputEl.outerHTML
        .replace(/100%/g, "256")
        .split('d=""');
      this.slicedTemplateArr = slicedHTMLString.map((d) => {
        return encodeURIComponent(d);
      });
    }
  }

  updateFeImageUri(col, pathData) {
    this[`${col}PathData`] = pathData;
    const templateString = `${this.slicedTemplateArr[0]}d%3D%22${this.redPathData}%22${this.slicedTemplateArr[1]}d%3D%22${this.bluePathData}%22${this.slicedTemplateArr[2]}`;

    requestAnimationFrame(() => {
      this.feImgEl.setAttribute(
        "xlink:href",
        `data:image/svg+xml;charset=utf-8,${templateString}`
      );
    });
  }

  updatePath(col, pathData) {
    requestAnimationFrame(() => {
      this[`${col}blur`].setAttribute("d", pathData);
    });
  }
}

const setMapScale = (e) => {
  const displacementScale = e.target.value;
  feDisplacementMap.setAttribute("scale", displacementScale);
};

testSVGFragmentToFeImg().then((val) => {
  const urlEncodedDisplacementMap = new DisplacementMapUpdater("#feimg", val);

  adjustSafariScreenDensity(document.getElementById("feimage-input"));
  feDisplacementMap.setAttribute('scale', slider.value);

  redPathElems = document.querySelectorAll(".red-path");
  bluePathElems = document.querySelectorAll(".blue-path");

  new PathData(
    "red",
    urlEncodedDisplacementMap,
    redPathElems,
    demoEl,
    "#feimage-input",
    val
  );
  new PathData(
    "blue",
    urlEncodedDisplacementMap,
    bluePathElems,
    demoEl,
    "#feimage-input",
    val
  );

  for (let el of thumbs) {
    el.addEventListener("click", (e) => {
      const src = e.target.getAttribute("src");
      filteredPic.setAttribute("href", src);
    });
  }
  slider.addEventListener("input", setMapScale, false);
  slider.addEventListener("change", setMapScale, false);
});

              
            
!
999px

Console