The canvas implements a small demo with dynamic effects (scrolling circle)

Show results:

One: Analyzing the problem:

  1. First of all, the static structure is a box, and there is a circle inside the box.
  2. The circle is moving inside the box.
  3. The process of moving reflects randomness.
  4. There will be a bounce effect when the circle hits the border of the box.

Two: Problem-solving ideas:

  1. The api used explicitly is the canvas canvas. Dynamic effects use timers.
  2. First draw out the static structure.
  3. Calculate the coordinates of the center of the circle as it moves.
  4. Calculate the conditions for the circle to bounce when it hits the border of the box.
  5. Effects are implemented dynamically using timers.

Three: Code implementation:

<!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>动态</title>
</head>

<body>
    <canvas id="myCanvas" width="500px" height="500px" style="border: 1px solid black;"></canvas>
    <script>
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");

        function rand(mun) {
            return Math.floor(Math.random() * mun + 1)
        }
        var arcX = 40;
        var arcY = 40;
        var arcR = 40;
        var radX = rand(10);
        var radY = rand(10);
        setInterval(function () {
            ctx.clearRect(0, 0, 500, 500);
            arcX += radX;
            arcY += radY;
            if (arcX > c.width - arcR) {
                radX = -radX;
            }
            if (arcX < arcR) {
                radX = Math.abs(radX);
            }
            if (arcY > c.width - arcR) {
                radY = -radY;
            }
            if (arcY < arcR) {
                radY = Math.abs(radY);
            }
            ctx.beginPath();
            ctx.fillStyle = "blue";
            ctx.arc(arcX, arcY, 40, 0, 2 * Math.PI);
            ctx.fill();
        }, 20)
    </script>
</body>

</html>

Four: Cool case sharing:

Guess you like

Origin blog.csdn.net/m0_50789201/article/details/124362303