1.题目要求:
请写一个html页面,鼠标每次点击屏幕,
在以点击处为中心的地方会出现一个旋转的六边形,直径50px,
顺时针旋转,每2秒钟转一圈,旋转要流畅。
2.具体实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#container .box{
position:absolute;
width:100px;
height:100px;
border:1px solid black;
}
#container .box div{
position:absolute;
background:red;
top:50%;
left:50%;
}
@keyframes demo{
0%{
transform:rotate(0deg)
}
100%{
transform:rotate(360deg);
}
}
#container .box{
animation:demo 2s linear infinite;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
let container=document.getElementById("container");
window.onclick=function(e){
//获取鼠标的点击坐标
let x=e.clientX;
let y=e.clientY;
let width_dom=Math.sqrt(25*25-12.5*12.5)*2;
console.log(width_dom);
console.log("x:"+x,"y:"+y);
/*定义一个容器用于存放对应的六边形*/
let box=document.createElement("div");
box.className='box';
box.style.top=y+'px';
box.style.left=x+'px';
box.style.marginTop=-50+'px';
box.style.marginLeft=-50+'px';
//计算并绘制这个六边形
/*创建三个矩形,旋转一定角度形成六边形*/
let fragment=document.createDocumentFragment();
let dom;
for(let i=0;i<3;i++){
dom=document.createElement("div");
dom.style.width=width_dom+'px';
dom.style.height=25+'px';
dom.style.marginTop=-(25/2)+'px';
dom.style.marginLeft=-(width_dom/2)+'px';
if(i===1){
dom.style.transform='rotate(118deg)';
}else if(i===2){
dom.style.transform='rotate(60deg)';
}else{
}
fragment.appendChild(dom);
}
box.appendChild(fragment);
container.appendChild(box);
}
</script>
</body>
</html>
3.运行效果:
4.总结:
(1)如何获取鼠标的当前坐标:e.cleintX, e.clientY;
(2)旋转效果的实现:将需要旋转的元素放在一个容器中,然后旋转这个容器即可。