如何使imageObject在圆形路径中移动?或更具体地说,要做到这一点需要什么数学公式?

我需要将setInterval与计算图片新坐标的函数一起使用。 setInterval应该每秒至少调用20次。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Graphics and animation using HTML5 Canvas</title>
        <style>
            #the-canvas { border: 1px dashed gray }
        </style>
        <script>
            addEventListener('load', function() {
                var x = document.getElementById("the-canvas");
                var y = x.getContext("2d");

                var imageObject = new Image();

                imageObject.onload = function() {
                    y.drawImage(imageObject, 100, 200);
                };

                imageObject.src = "image.jpg";

            });
        </script>
    </head>
    <body>
        <canvas id="the-canvas" width="500" height="400">
            Your browser does not support the &lt;canvas&gt; element.
        </canvas>
    </body>
</html>

最佳答案

所需的数学公式在一维上是余弦,而在另一维上是正弦。

像这样:

        addEventListener('load', function() {
            var x = document.getElementById("the-canvas");
            var y = x.getContext("2d");

            var imageObject = new Image();

            var step = 0, radius = 50, speed = 0.05;

            function spin() {
                y.clearRect(0, 0, x.width, x.height);
                y.drawImage(imageObject, 100 + radius * Math.cos(speed * step), 200 + radius * Math.sin(speed * step));
                ++step;
            }

            imageObject.onload = function() {
                y.drawImage(imageObject, 100, 200);
                setInterval(spin, 50); // 20 fps
            };

            imageObject.src = "image.jpg";

        });

关于javascript - 纯粹使用JavaScript在循环路径中移动图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33595359/

10-11 12:53