js svg实现“倒8”形状loading动画

848 阅读1分钟

实现一个'倒8'形状的动画效果。用于加载等待过程的loading停留阶段。

html结构

<svg class="loadingBox" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" version="1.1">
  <g transform="translate(50,50) scale(1,-1)">
    <path class="loading_path" d="M0 0 C -60 -62, -60 62, 0 0 C 60 -62, 60 62, 0 0" stroke="#38F" stroke-width="4" stroke-linecap="round" fill="transparent">
    </path>
  </g>
</svg>

css部分

.loadingBox{
  width: 300px;
  height: 300px;
}
@keyframes load {
  from {
    stroke-dashoffset: var(--fromDashoffset);
  }
  to{
    stroke-dashoffset: var(--toDashoffset);
  }
}
.loadingBox .loading_path{
  --offsetValue: 0;
  --fromDashoffset: 0;
  --toDashoffset: 247;
  stroke-dasharray: 217,30;
  stroke-dashoffset: var(--offsetValue);
  animation: load 1800ms linear infinite;
}

javascript 部分

const namespace = "http://www.w3.org/2000/svg";
const  dom_path = document.getElementsByTagNameNS(namespace, `path`)[0];
const  dom_svg = document.getElementsByTagNameNS(namespace, `svg`)[0];
// console.log(dom_path.getTotalLength(),'getTotalLength()')
const getOffSetVal = ()=>{
  const val = getComputedStyle(dom_path).strokeDashoffset;
  const newValue = val.substr(0, val.length - 2);
  return newValue;
}
dom_svg.addEventListener(`mousedown`,(e)=>{
  const value = getOffSetVal();
  dom_path.style.setProperty(`--offsetValue`,`${value}`);
  dom_path.style.animation=`none`;
})
dom_svg.addEventListener(`mousemove`,(e)=>{ })
dom_svg.addEventListener(`mouseup`,(e)=>{
  const value = getOffSetVal()
  dom_path.style.setProperty(`--offsetValue`,`${value}`);
  dom_path.style.setProperty(`--fromDashoffset`,`${value}`);
  dom_path.style.setProperty(`--toDashoffset`,`${value-247}`);
  dom_path.style.animation= `load 2000ms linear infinite`;
})

效果图:

loading.gif codepen链接