)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Line to Line Intersection

  1. // line to line intersection https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
  2. function lineIntersection(p1, p2, p3, p4) {
  3.   let ip = { x: 0, y: 0 };
  4.   // rare case where I use `_` in a non-constant variable name
  5.   // to make this easy to read to with the wikipedia info
  6.   const x4_x3 = p4.x - p3.x;
  7.   const y4_y3 = p4.y - p3.y;
  8.   const x2_x1 = p2.x - p1.x;
  9.   const y2_y1 = p2.y - p1.y;
  10.   const x1_x3 = p1.x - p3.x;
  11.   const y1_y3 = p1.y - p3.y;
  12.   let nx, ny, dn;
  13.  
  14.   nx = x4_x3 * y1_y3 - y4_y3 * x1_x3;
  15.   ny = x2_x1 * y1_y3 - y2_y1 * x1_x3;
  16.   dn = y4_y3 * x2_x1 - x4_x3 * y2_y1;
  17.  
  18.   nx /= dn;
  19.   ny /= dn;
  20.  
  21.   // has intersection
  22.   if (nx >= 0 && nx <= 1 && ny >= 0 && ny <= 1) {
  23.     ny = p1.y + nx * y2_y1;
  24.     nx = p1.x + nx * x2_x1;
  25.     ip.x = nx;
  26.     ip.y = ny;
  27.   } else {
  28.     // no intersection
  29.     ip = null;
  30.   }
  31.   return ip;
  32. }
  33.  
  34. const el = document.body.appendChild(
  35.   document.createElement('div'));
  36.  
  37. // hard coding line values for simplicity and ease of understanding
  38. el.innerHTML = `
  39.   <svg width="100%" height="100%" viewBox="0 0 550 496">
  40.     <path id='path' d="M 10 10 L 300 300 M 100 10 L 160 320" stroke="black" fill='none' vector-effect="non-scaling-stroke"/>
  41.     <rect id="intersecton" x="0" y="0" width="10" height="10" fill="red" />
  42.   </svg>
  43.   <style>
  44.     svg, div, body, html {
  45.       overflow: visible; 
  46.       height: 100%; 
  47.       width: 100%;
  48.       margin: 0; padding: 0;
  49.     }
  50.   </style>
  51. `;
  52.  
  53. const loc = lineIntersection(
  54.   {x: 10, y: 10}, {x: 300, y:300},
  55.   {x: 100, y: 10}, {x: 160, y:320}
  56. );
  57.  
  58. // subtract half the size of the rect from both axis to center it
  59. intersecton.x.baseVal.value = loc.x - 5;
  60.  
  61. // @NOTE: using the `id` global `window.intersection` 
  62. // is just good for demos - little risky for real stuff 
  63. // since it lends itself to easy collision
  64. window.intersecton.y.baseVal.value = loc.y - 5;

Line to line intersection rendered with SVG.

Save Large Canvas

  1. // https://stackoverflow.com/questions/38781968/problems-downloading-big-filemax-15-mb-on-google-chrome
  2. function dataUriToBlob(dataURI) {
  3.   const binStr = atob(dataURI.split(',')[1]);
  4.   const len = binStr.length;
  5.   const arr = new Uint8Array(len);
  6.   const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
  7.   for (let i = 0; i < len; i++) {
  8.     arr[i] = binStr.charCodeAt(i);
  9.   }
  10.  
  11.   const blob = new Blob([arr], {
  12.     type: mimeString
  13.   });
  14.  
  15.   return URL.createObjectURL(blob);
  16. }
  17.  
  18. const save = document.createElement('a');
  19. save.innerText = 'save this big image';
  20. document.body.appendChild(save);
  21.  
  22. const canvas = document.createElement('canvas');
  23. const c = canvas.getContext('2d');
  24.  
  25. canvas.width = window.innerWidth * 4;
  26. canvas.height = window.innerHeight * 4;
  27. canvas.style.transformOrigin = '0 0';
  28. canvas.style.transform = `scale(0.14)`;
  29. document.body.appendChild(canvas);
  30.  
  31. c.fillStyle = 'black';
  32. c.fillRect(0, 0, canvas.width, canvas.height);
  33.  
  34. const size = Math.max(window.innerWidth, window.innerHeight);
  35.  
  36. // draw some rectangles
  37. c.globalCompositeOperation = 'difference'
  38. for (let i = 0; i < 100; i++) {
  39.   const angle = Math.random() * 180 + 180;
  40.   const color = `hsl(${angle}deg, 50%, 50%)`;
  41.   c.fillStyle = color;
  42.   const width = Math.random() * size + 100;
  43.   const height = Math.random() * size + 100;
  44.   const x = Math.random() * canvas.width - width / 2;
  45.   const y = Math.random() * canvas.height - height / 2;
  46.   c.fillRect(
  47.     x, 
  48.     y, 
  49.     width, 
  50.     height);
  51. }
  52.  
  53. save.download = 'big-image';
  54. save.href = dataUriToBlob(canvas.toDataURL());

Weirdly if you try to save a massive data URI to a file (> 15mb) it will just fail. In order to do this properly, you need to convert to a blob first and then save. I encountered this at some point and learned of the solution from user doppelgreener over at stack overflow. Take a look at the post here.

SVG Relative Touch/Mouse Events

  1. const hasTouch =
  2.   navigator.maxTouchPoints != null && navigator.maxTouchPoints > 0;
  3.  
  4. const el = document.body.appendChild(document.createElement('div'));
  5.  
  6. el.innerHTML = `
  7.   <svg id="mainSvg" width="100%" height="100%" viewBox="0 0 800 800">
  8.     <g transform="translate(100, 100) scale(0.8, 0.8) rotate(25, 400, 400)">
  9.       <rect x="0" y="0" width="800" height="800" fill="#ccc" stroke="none"/>
  10.       <text x="10" y="30" font-size="30px">click/tap the box</text>
  11.     </g>
  12.   </svg>
  13.   <style>
  14.     svg, div, body, html {
  15.       height: 100%;
  16.       width: 100%;
  17.       margin: 0; padding: 0;
  18.     }
  19.  
  20.     svg {
  21.       overflow: hidden;
  22.     }
  23.   </style>
  24. `;
  25. function createSvg(type) {
  26.   return document.createElementNS('http://www.w3.org/2000/svg', type);
  27. }
  28.  
  29. // mouse or touch location is always relative to the svg
  30. // any css transformations on the svg are only accounted for in 
  31. // Chrome unfortunately
  32. function svgTouch(e, svgEl) {
  33.   const touches = e.touches;
  34.   let locX, locY;
  35.   if (touches != null && touches.length > 0) {
  36.     locX = touches[0].clientX;
  37.     locY = touches[0].clientY;
  38.   } else {
  39.     locX = e.clientX;
  40.     locY = e.clientY;
  41.   }
  42.  
  43.   const pt = svgEl.createSVGPoint();
  44.   pt.x = locX;
  45.   pt.y = locY;
  46.  
  47.   const newPnt = pt.matrixTransform(svgEl.getScreenCTM().inverse());
  48.   return { locX: newPnt.x, locY: newPnt.y };
  49. }
  50.  
  51. document.addEventListener(hasTouch ? 'touchstart' : 'mousedown', e => {
  52.   // global id `mainSvg` :P
  53.   const { locX, locY } = svgTouch(e, mainSvg);
  54.  
  55.   const circle = createSvg('circle');
  56.   circle.cx.baseVal.value = locX;
  57.   circle.cy.baseVal.value = locY;
  58.   circle.r.baseVal.value = 20;
  59.   circle.style.fill = 'blue';
  60.  
  61.   mainSvg.appendChild(circle);
  62. });

This snippet shows how to get relative mouse/touch coordinates within an SVG element. The main trick here is on line 50… pt.matrixTransform(svgEl.getScreenCTM().inverse()); – we get the inverse transformation matrix of the “mainSvg” node and transform the mouse/touch coordinates by it.

Beware, when this was posted, as noted in the comments – CSS transforms on the SVG element or any of its parents won’t be accounted for in the `getScreenCTM` call in any browsers other than Chrome. There is an open Firefox issue for this I believe…

// dom // graphics // javascript // math // matrix // svg // tricks

Quick Touch Events 2 (easing)

  1. // no scrolling on mobile
  2. document.addEventListener('touchmove', e => e.preventDefault(), {
  3.   passive: false
  4. });
  5.  
  6. const hasTouch =
  7.   navigator.maxTouchPoints != null && navigator.maxTouchPoints > 0;
  8. // looking forward to `navigator?.maxTouchPoints > 0`
  9. // being better supported
  10.  
  11. function touchify(e) {
  12.   const touch = [];
  13.   touch.x = touch.y = 0;
  14.  
  15.   if (e.touches != null && e.touches.length > 0) {
  16.     touch.x = e.touches[0].clientX;
  17.     touch.y = e.touches[0].clientY;
  18.     for (let i = 0; i < e.touches.length; i++) {
  19.       touch[i] = e.touches[i];
  20.     }
  21.   } else {
  22.     touch.x = e.clientX;
  23.     touch.y = e.clientY;
  24.     touch[0] = { clientX: e.clientX, clientY: e.clientY };
  25.   }
  26.   return touch;
  27. }
  28.  
  29. let moveOrTouchMove;
  30.  
  31. if (hasTouch) {
  32.   moveOrTouchMove = 'touchmove';
  33. } else {
  34.   moveOrTouchMove = 'mousemove';
  35. }
  36.  
  37. function dot(x, y, radius, color) {
  38.   const el = document.createElement('div');
  39.   const size = `${radius * 2}px`;
  40.   Object.assign(el.style, {
  41.     position: 'absolute',
  42.     left: `${x}px`,
  43.     top: `${y}px`,
  44.     width: size,
  45.     height: size,
  46.     transform: `translate(${-radius}px, ${-radius}px)`,
  47.     borderRadius: '50%',
  48.     background: color
  49.   });
  50.   el.classList.add('dot');
  51.   document.body.appendChild(el);
  52.   return el;
  53. }
  54.  
  55. let dotX = 100,
  56.   dotY = 100,
  57.   touchX = 200,
  58.   touchY = 150,
  59.   damp = 12,
  60.   dotEl = dot(dotX, dotY, 20, 'red');
  61.  
  62. document.addEventListener(moveOrTouchMove, e => {
  63.   const { x, y } = touchify(e);
  64.   touchX = x;
  65.   touchY = y;
  66. });
  67.  
  68. function loop() {
  69.   dotX += (touchX - dotX) / damp;
  70.   dotY += (touchY - dotY) / damp;
  71.   Object.assign(dotEl.style, {
  72.     left: `${dotX}px`,
  73.     top: `${dotY}px`
  74.   });
  75.   window.requestAnimationFrame(loop);
  76. }
  77. loop();

Move your mouse on desktop or your finger on mobile – watch the red dot follow…

This is a simpler version of some of the things used in yesterdays post – just a quick way to normalize touch events – just one of many ways to do this – for simple stuff this is my goto.

If you want to try it out on its own page – take a look here (specifically good for trying it on mobile).

You’ll probably want a to use a meta tag like this – for the full effect.

  1. <meta name="viewport" content="width=device-width, initial-scale=1.0">

Quick Touch Events

  1. // no scrolling on mobile
  2. document.addEventListener("touchmove", e => e.preventDefault(), {
  3.   passive: false
  4. });
  5.  
  6. // has more than one touch point
  7. const hasTouch =
  8.   navigator.maxTouchPoints != null && navigator.maxTouchPoints > 0;
  9.  
  10. function touchify(e) {
  11.   const touch = [];
  12.   touch.x = touch.y = 0;
  13.  
  14.   if (e.touches != null && e.touches.length > 0) {
  15.     touch.x = e.touches[0].clientX;
  16.     touch.y = e.touches[0].clientY;
  17.     for (let i = 0; i < e.touches.length; i++) {
  18.       touch[i] = e.touches[i];
  19.     }
  20.   } else {
  21.     touch.x = e.clientX;
  22.     touch.y = e.clientY;
  23.     touch[0] = { clientX: e.clientX, clientY: e.clientY };
  24.   }
  25.   return touch;
  26. }
  27.  
  28. let clickOrTouchEnd,
  29.   downOrTouchStart,
  30.   enterOrTouchStart,
  31.   moveOrTouchMove,
  32.   upOrTouchEnd,
  33.   leaveOrTouchEnd;
  34.  
  35. if (hasTouch) {
  36.   clickOrTouchEnd = "touchend";
  37.   downOrTouchStart = "touchstart";
  38.   enterOrTouchStart = "touchstart";
  39.   moveOrTouchMove = "touchmove";
  40.   upOrTouchEnd = "touchend";
  41.   leaveOrTouchEnd = "touchend";
  42. } else {
  43.   clickOrTouchEnd = "click";
  44.   downOrTouchStart = "mousedown";
  45.   enterOrTouchStart = "mouseenter";
  46.   moveOrTouchMove = "mousemove";
  47.   upOrTouchEnd = "mouseup";
  48.   leaveOrTouchEnd = "mouseleave";
  49. }
  50.  
  51. function dot(x, y, radius, color) {
  52.   const el = document.createElement("div");
  53.   const size = `${radius * 2}px`;
  54.   Object.assign(el.style, {
  55.     position: "absolute",
  56.     left: `${x}px`,
  57.     top: `${y}px`,
  58.     width: size,
  59.     height: size,
  60.     transform: `translate(${-radius}px, ${-radius}px)`,
  61.     borderRadius: "50%",
  62.     background: color
  63.   });
  64.   el.classList.add("dot");
  65.   document.body.appendChild(el);
  66.   return el;
  67. }
  68.  
  69. let down = false;
  70. let lastTouch;
  71. document.addEventListener(downOrTouchStart, e => {
  72.   const { x, y } = touchify(e);
  73.   dot(x, y, 30, `rgba(255, 0, 0, 0.2)`);
  74.   down = true;
  75. });
  76.  
  77. document.addEventListener(moveOrTouchMove, e => {
  78.   if (down) {
  79.     const touches = touchify(e);
  80.     // draw more than one touch
  81.     for (let i = 0; i < touches.length; i++) {
  82.       const touch = touches[i];
  83.       dot(touch.clientX, touch.clientY, 10, `rgba(0, 0, 155, 0.2)`);
  84.     }
  85.  
  86.     lastTouch = touches[0];
  87.   }
  88. });
  89.  
  90. document.addEventListener(upOrTouchEnd, e => {
  91.   if (down) {
  92.     dot(lastTouch.clientX, lastTouch.clientY, 20, `rgba(0, 155, 0, 0.2)`);
  93.     down = false;
  94.   }
  95. });

Draw with your mouse by clicking, holding down and dragging…

I often use some variation of this depending on the project… This snippet normalizes touch events in a simple way, prevents scrolling and gives an example of how to handle multi-touch.

You’ll probably want a to use a meta tag like this – for the full effect.

  1. <meta name="viewport" content="width=device-width, initial-scale=1.0">
snippet.zone ~ 2021-24 /// {s/z}