JS圆碰撞
1.圆碰撞可以进行小游戏的开发
常见问题:如果在正方体盒子的情况下设置圆角,则会保留正方体的特性,在未接触到圆形的时候就会发生变色
下面是HTML的部分:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #div1{ width: 100px; height: 100px; background: #00b38a; position: absolute; left: 0; top: 0; border-radius: 50%; } #div2{ width: 100px; height: 100px; background:yellow; position: absolute; left: 500px; top: 200px; border-radius: 50%; } </style> </head> <body> <div id="div1"></div> <div id="div2"></div> </body> </html>
下面是JS的部分:
<script> var div1=document.getElementById('div1') var div2=document.getElementById('div2') div1.onmousedown=function (event) { //获取本次事件,鼠标位置 console.log(event.clientX) console.log(div1.offsetLeft) var chaX=event.clientX-div1.offsetLeft var chaY=event.clientY-div1.offsetTop document.onmousemove=function (event) { console.log(event.clientX) div1.style.left=event.clientX-chaX+'px' div1.style.top=event.clientY-chaY+'px' if((div1.offsetWidth/2+div2.offsetWidth/2)*(div1.offsetWidth/2+div2.offsetWidth/2) >(div2.offsetLeft-div1.offsetLeft)*(div2.offsetLeft-div1.offsetLeft)+(div2.offsetTop-div1.offsetTop) *(div2.offsetTop-div1.offsetTop)){ div2.style.background="red" }else{ div2.style.background="" } } document.onmouseup=function () { document.onmousemove=null } } </script>
实现效果: