请马上登录,朋友们都在花潮里等着你哦:)
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 马黑黑 于 2025-8-6 20:37 编辑
<style>
.ma {
margin: 30px auto;
width: 400px;
height: 400px;
background: tan;
}
</style>
<div class="ma"></div>
<p id="pathData" style="text-align: center;"></p>
<script>
const ma = document.querySelector('.ma'); // 待操作元素
const total = 3; // 顶点数(多边形的边总数)
// 获取顶点坐标值 :参数 r 为多边形外接圆半径
const getPoints = (r) => {
const a = 360 / total; // 平均角度
const R = ma.clientWidth / 2; // 外接圆半径
let res = []; // 坐标值数组
// 遍历所有顶点计算其坐标值
Array.from({length: total}).forEach((_,k) => {
const x = R + r * Math.cos(Math.PI / 180 * a * k);
const y = R + r * Math.sin(Math.PI / 180 * a * k);
res.push({x: x, y: y});
});
res.push(res[0]); //回到原点
return res; // 返回数组
};
const ar1 = getPoints(200); // 外层坐标集 半径要大于里层半径
const ar2 = getPoints(180).reverse(); // 里层坐标集(反转) 半径要小于外层半径
let path = 'M'; // 路径
ar1.forEach((ar, key) => path += `${ar.x}, ${ar.y} `); // 加入外层路径
ar2.forEach((ar, key) => path += `${ar.x}, ${ar.y} `); // 加入里层路径
ma.style.clipPath = `path('${path}')`; // 切割
pathData.textContent = 'clip-path: ' + ma.style.clipPath + ';'; // clip-path属性
</script>
代码可以存为本地 .html 文档后运行(建议,酱紫可以修改重要的数据),或到我的网站直接运行:内切多边形代码及演示,还可以将代码复制到 pencil code 进行代码调试。
|