javascript - Javascript根据光标位置旋转三角形剪辑路径
问题描述
我需要创建一个剪辑路径三角形,并且它的一个顶点需要锚定在中心,并且它的形状根据光标的移动旋转以形成一种手电筒,但我坚持用边形成三角形等长并将其拉伸到屏幕边缘。此外,当移动到屏幕顶部/底部的中间时,它的面积也趋于零这是我的代码:
<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}%)`;
});
解决方案
我的数学可能生锈了,但这样的事情可能对你有用:
var container = document.querySelector(".container");
var rayRadius = 0.3; /* Pi radians */
window.addEventListener("mousemove", (e) => {
let katX = window.innerWidth/2 - e.pageX;
let katY = window.innerHeight/2 - e.pageY;
let atan = Math.atan( katX/katY );
let ray1angle = atan + rayRadius;
let ray2angle = atan - rayRadius;
let cover = Math.max(window.innerWidth, window.innerHeight);
let ray1x = window.innerWidth/2 - Math.sign(katY)*Math.sign(ray1angle)*cover;
let ray1y = window.innerHeight/2 - Math.sign(katY)*1/Math.tan(ray1angle) * Math.sign(ray1angle)*cover;
let ray2x = window.innerWidth/2 - Math.sign(katY)*Math.sign(ray2angle)*cover;
let ray2y = window.innerHeight/2 - Math.sign(katY)*1/Math.tan(ray2angle) * Math.sign(ray2angle)*cover;
container.style.clipPath = `polygon(50% 50%,${ray1x}px ${ray1y}px,${ray2x}px ${ray2y}px)`;
});
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 {
background: rebeccapurple;
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;
}
<div class="container">
some lorem ipsum here
</div>
同样在JS Fiddle上。
推荐阅读
- vmware - kubctl 不从公共注册表中提取图像,但 docker pull 有效
- javascript - .map 不是函数.....不渲染表
- python - Tensorflow saved_model.load 问题
- f# - 无法在 F# 中使用 json.net 序列化记录
- javascript - 使用 asp.net 母版页定位对 html 元素的 javascript 引用
- r - 使用 geom_smooth 后是否有 ggplot2 函数可以删除原始线条?
- discord.js - 是否可以选择将多个机器人帐户连接到一个 discord.js 代码?
- php - MySQL 查询到 PHP 查询
- python - 将具有一定行数的数据列从多个文本文件中提取到一个文本文件中
- python - 难以理解类