Categories
Web development

Baggage Scan /SVG & JavaScript Animation

SVG luggage

Scan the luggage!

Demo:

To create the animation you need to have two images of the luggage (closed and open) in SVG/ png format (to practice only you can use mine which I drew in Adobe Illustrator CC) and follow the steps below:

  1. Add HTML
  2. Add CSS
  3. Add JavaScript
luggage
luggage inside

Step1.

Add HTML

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink">
  <rect width="100%" height="auto" fill="#ffb4a2"/>
  <image xmlns:xlink= "http://www.w3.org/1999/xlink" xlink:href="https://lenadesign.org/wp-content/uploads/2020/06/luggage.png?w=640" width="100%" height="100%" />
</svg>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink">
  <defs>
    <clipPath id="mask">
      <circle id="scan" cx="50%" cy="50%" r="8%" />
    </clipPath>
  </defs>
  <g clip-path="url(#mask)">
    <rect width="100%" height="100%" fill="#434373"/>
    <image xmlns:xlink= "http://www.w3.org/1999/xlink" xlink:href="https://lenadesign.org/wp-content/uploads/2020/06/luggage-inside.png?w=640" width="100%" height="100%" />
  </g>
</svg>

Step2.

Add CSS

body {
  background-color:#ffb4a2;
  height: 100vh;  
}

svg {
  position: absolute;
  top: 100px;
  left: 15%;
  width: 70%;
  height: 70%;
}

Step3.

Add JavaScript

var svgElement = document.querySelector("svg");
var maskedElement = document.querySelector("#scan");
var svgPoint = svgElement.createSVGPoint();

function cursorPoint(e, svg) {
    svgPoint.x = e.clientX;
    svgPoint.y = e.clientY;
    return svgPoint.matrixTransform(svg.getScreenCTM().inverse());
}

function update(svgCoords) {
    maskedElement.setAttribute('cx', svgCoords.x);
    maskedElement.setAttribute('cy', svgCoords.y);
}

window.addEventListener('mousemove', function(e) {
  update(cursorPoint(e, svgElement));
}, false);

document.addEventListener('touchmove', function(e) {
    e.preventDefault();
    var touch = e.targetTouches[0];
    if (touch) {
        update(cursorPoint(touch, svgElement));
    }
}, false);

Enjoy coding!

Read also:

SVG Draw on Scroll

SVG Handwriting Animation

SVG Path Drawing Animation