html+css如何设计图片在页面上自由浮动,遇边缘反弹

如何只使用HTML+CSS实现图片在页面上自由浮动,碰到页面边界后反弹,遇鼠标悬浮时停止浮动,点击“关闭”后隐藏


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> -->
    <title>document</title>
    <style type="text/css">
      #div1 {
        width: 300px;
        height: 300px;
        padding: 0;
        margin: 0;
        position: fixed;
        left: 0;
        top: 0;
      }
      #div1 img {
        width: 300px;
        height: 300px;
      }
    </style>
  </head>
  <body>
    <div id="div1">
      <img id="ad" src="1.png" alt="" />
      <button onclick="closeAd()">关闭</button>
    </div>
    <script type="text/javascript">
      // 参考来源: https://blog.csdn.net/zxh996/article/details/118655180
      window.onload = function () {
        //获取元素
        var div1 = document.getElementById("div1");
        var w = document.documentElement.clientWidth;
        var h = document.documentElement.clientHeight;
        var gox = 1;
        var goy = 1;
        //广告漂浮
        function move() {
          var x = div1.offsetLeft;
          var y = div1.offsetTop;
          if (x > w - 300 || x < 0) gox = -gox;
          div1.style.left = x + 10 * gox + "px";
          if (y > h - 300 || y < 0) goy = -goy;
          div1.style.top = y + 10 * goy + "px";
        }
        //漂浮定时器
        var timer = setInterval(move, 30);
        //移入移出时广告的浮动
        div1.onmouseover = function () {
          clearInterval(timer);
        };
        div1.onmouseout = function () {
          timer = setInterval(move, 30);
        };
        //点击一次跳转到另一个页面,点击两次广告消失
        ad.onclick = function () {
          var neww = window.open("_blank");
          neww.location = "http://www.baidu.com";
        };
      };
      function closeAd() {
        var div1 = document.getElementById("div1");
        div1.style.display = "none";
      }
    </script>
  </body>
</html>

代码实现起来较复杂,给提供个思路看看能否自己实现。
1、图片必须使用position: fixed定位,可以完全脱离文档流。
2、做一个定时器,计算这个图片的top 和 left位置,让其一直在移动。
3、在移动的时候要时刻计算top + 本身宽度是否超越了边界,如果超越,改变起运动轨迹top 和 left。
4、鼠标悬浮图片后,clearInterval这个定时器,不悬浮时重新启用定时器。