Js 实现圆形碰撞

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            position: absolute;
            border-radius: 50%
        }

        #div1 {
            background: red;
            left: 200px;
            top: 200px
        }

        #div2 {
            background: lightgreen
        }
    </style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
<script>
    const div1 = document.getElementById('div1')
    const div2 = document.getElementById('div2')
    div2.onmousedown = (event) => {
        console.log(event.clientX, event.clientY)
        const x = event.clientX,
            y = event.clientY,
            l = div2.offsetLeft,
            t = div2.offsetTop
        document.onmousemove = (event) => {
            console.log("鼠标x轴" + (event.clientX - x),
                ",鼠标y轴" + (event.clientY - y))
            div2.style.left = l + event.clientX - x + 'px'
            div2.style.top = t + event.clientY - y + 'px'
            const a = div1.offsetTop + div1.offsetHeight / 2
                - (div2.offsetTop + div2.offsetHeight / 2),
                b = div1.offsetWidth / 2 + div1.offsetLeft
                    - (div2.offsetLeft + div2.offsetWidth / 2)
            if (a * a + b * b <=
                (div2.offsetWidth / 2 + div1.offsetHeight / 2)
                * (div2.offsetWidth / 2 + div1.offsetHeight / 2)) {
                div2.style.background = '#000'
            } else {
                div2.style.background = ''
            }
        }
        document.onmouseup = () => {
            document.onmousemove = null
        }
    }
</script>

 

posted @ 2021-12-09 10:15  小马学编程  阅读(41)  评论(0)    收藏  举报