mardi 21 septembre 2021

Javascript rotate triangular clip path according to cursor position

I need to create a clip-path triangle and one of its vertices need to be anchored in the center, and its shape rotates according to the movement of the cursor to form a kind of flashlight, but I am stuck with forming triangular with sides of the equal length and stretching it out to the edges of the screen. Also it's area tends to zero as moving to the middle of top/bottom side of the screen Here is my code:

<div class="container">
   some lorem ipsum here
</div>
/* css */
body{
    box-sizing: border-box;
    margin:0;
    padding:0;
    height: 100vh;
    width:100vw;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: aliceblue;
    
}
.container{
    font-size: 2rem;
    clip-path: polygon(50% 50%,30% 100%,70% 100%);
   height: 100%;
   width: 100%;
   display: flex;
   justify-content: center;
   align-items: center;
   overflow: hidden;
}
//js
let container = document.querySelector(".container");
window.addEventListener("mousemove", (e) => {
  console.log(
    Math.round((e.pageX / window.innerWidth) * 100),
    Math.round((e.pageY / window.innerHeight) * 100)
  );

  const x = Math.round((e.pageX / window.innerWidth) * 100);
  const y = Math.round((e.pageY / window.innerHeight) * 100);
  container.style.clipPath = `polygon(50% 50%,${x}% ${y - 10}%,${x}% ${y + 10}%)`;
});


Here is what I want to get, but using clip-path so I could see only the content which is cliped:

Aucun commentaire:

Enregistrer un commentaire