SVG Intersection Observer API

Experiment showing how/whether the SVG and Intersetion Observer APIs play nice together.

by Buck Evan

HTML

<h1>
  SVG Intersection Observer API
</h1>
<svg id=svg>
  <circle r=10></circle>
</svg>

CSS

html * {
  width: 100%;
  margin: 0;
  padding: 10px;
  box-sizing: border-box;

  /* Lets me see each element */
  background: hsla(0deg, 0%, 0%, 15%);
  border: 1px solid black;
}

html {
  background: white;
}

body {
  min-height: 100vh;
}

JavaScript

startObserver()
window.addEventListener('mousemove', onMousemove)


function startObserver() {
  // Almost verbatim from MDN docs:
  //   https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
  let options = {
    root: document.querySelector('#svg'),
    rootMargin: '0px',
    threshold: 0.50,
  }

  let observer = new IntersectionObserver(onIntersection, options);

  let target = document.querySelector('circle');
  observer.observe(target);
}

function onIntersection(entries, observer) {
  // Simply log all intersectiono entries.
  console.log(observer)
  console.log("intersections:")
  entries.forEach(function(entry) {
    console.log(entry)
    // This code is just a wild guess, but it still won't fire a second time.
    observer.observe(entry.target)
  })
}


function onMousemove(event) {
  // Circle will follow the mouse.
  var svg = document.querySelector('#svg')
  var point = svgPoint(svg, event.x, event.y)

  //console.log(event)
  //console.log(svg)
  //console.log(point)
  var circle = document.querySelector('circle')
  circle.setAttribute("cx", point.x)
  circle.setAttribute("cy", point.y)
}


// translate page to SVG co-ordinate
function svgPoint(svg, x, y) {
  var pt = svg.createSVGPoint();

  pt.x = x;
  pt.y = y;

  return pt.matrixTransform(svg.getScreenCTM().inverse());
}