先上效果。

一下是源码,格式化一下就好看了哈

<!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">    <title>Document</title>    <style>
    </style></head>
<body>    <canvas id="canvas"></canvas>    <script>        const step = 1;        const canvas = document.getElementById('canvas');        const ctx = cvsCtx = canvas.getContext('2d');        let direction = true;        let position = {            x: 0,            y: 0,        };        let speed = {            x: 3,            y: 1,        };        let box = {            width: 20,            height: 20,        };        canvas.width = 200;        canvas.height = 200;
        move();
        function drawImage() {            ctx.save();            let img = new Image();            img.src = "https://www.liuyanla.com/wp-content/uploads/2021/03/image-1.png";            img.onload = () => {                ctx.clearRect(0, 0, 200, 200);                cvsCtx.drawImage(img, 0, 0, img.width, img.height);                drawReact();            }            ctx.restore();        }
        function drawReact(){            ctx.save();            ctx.fillStyle = '#000';            ctx.fillRect(position.x, position.y, box.width, box.height);            ctx.restore();        }
        function move() {            drawImage();            requestAnimationFrame(() => {                if ((position.x > canvas.width - box.width - 1) || (position.x < 0)) {                    speed.x = -speed.x;                }                if (position.y > canvas.height - box.height || position.y < 0) {                    speed.y = -speed.y;                }
                position.x += speed.x;                position.y += speed.y;                move();            })        }    </script></body>
</html>

以上就是canvas绘制悬浮框的内容

微信交流(备注:前端)