画圆形运动轨迹

画圆形运动轨迹


<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Documenttitle>
    <style>
        .box {
            width: 20px;
            height: 20px;
            background: red;
            position: absolute;
            left: 600px;
            top: 300px;
        }
    style>
head>

<body>
    <div class="box">div>
    <script>
        //var x=a+Math.cos(angle*Math.PI/180)*r;
        //var y=b+Math.sin(angle*Math.PI/180)*r;
        //x,y盒子的位移,a,b盒子默认的位置, angle角度,r半径     angle*Math.PI/180弧度

        const oBox = document.querySelector('.box');
        let r = 200;
        let a = 200;
        let b = 300;
        let timer = null;
        let angle=0;
        oBox.onclick = function () {
            clearInterval(timer);
            timer = setInterval(function () {
                angle++;
                if(angle>=360){
                    clearInterval(timer);
                }
                oBox.style.left = a + Math.cos(angle * Math.PI / 180) * r + 'px';
                oBox.style.top = b + Math.sin(angle * Math.PI / 180) * r + 'px';
                let cDiv=document.createElement('div');
                cDiv.style.cssText=`width:5px;height:5px;background:blue;position:absolute;left:${oBox.offsetLeft}px;top:${oBox.offsetTop}px;`;
                document.body.appendChild(cDiv);
            }, 30);
        };
    script>
body>

html>

你可能感兴趣的:(js)