微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SVG元素跟随光标

如何解决SVG元素跟随光标

有人可以帮我吗? 我正在为“ pupil”元素而苦苦挣扎,该元素没有精确地跟随指针。我想做的事情与下面链接的参考相似。

Here is the Codepen I'm working on

Here is the reference I'm trying to follow

感谢所有支持和小费。

let eyeBall = document.querySelector(".eyeball"),pupil = document.querySelector(".pupil"),eyeArea = eyeBall.getBoundingClientRect(),pupilArea = pupil.getBoundingClientRect(),R = eyeArea.width/2,r = pupilArea.width/2,centerX = eyeArea.left + R,centerY = eyeArea.top + R;

document.addEventListener("mousemove",(e)=>{
  let x = e.clientX - centerX,y = e.clientY - centerY,theta = Math.atan2(y,x),angle = theta*180/Math.PI + 360;
  
  
  pupil.style.transform = `translateX(${R - r +"px"}) rotate(${angle + "deg"})`;
  pupil.style.transformOrigin = `${r +"px"} right`;
});
body{
  margin:0;
  padding:0;
  display: flex;
  width: 100%;
  height:100vh;
}
.eye{
  margin: auto;
/*   background:#ccc; */
}


.pupil {
  position:relative;
/*   transform:  rotate(390deg); */
/*   transform-origin: 20px center; */
}
<svg version="1.1" id="Livello_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" 
     viewBox="0 0 1000 1000" style="enable-background:new 0 0 1000 1000;" xml:space="preserve" height="400px" class="eye">
<g>
    
  <circle cx="499.52" cy="338.428" r="230" fill="yellow" class="eyeball" />
  
  <circle cx="499.52" cy="338.428" r="170.306" class="pupil" />
  
    
  
</g>
  
<path d="M728.777,19.651v70.071C668.44,34.06,587.887,499.52,0C312.911,161.092,151.819,338.428
    S312.911,676.856,676.856c88.368,168.92-34.06,229.258-89.722V890.83H311.747V1000h526.201V19.651H728.777z
     M499.52,567.686c-126.412,0-229.258-102.846-229.258-229.258S373.108,109.17,109.17s229.258,102.846,229.258,229.258
    S625.931,567.686,567.686z"/>
</svg>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。