纯粹使用JavaScript

时间:2015-11-08 15:02:07

标签: javascript canvas css-animations

如何让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>

1 个答案:

答案 0 :(得分:1)

所需的数学公式在一个维度上为余弦,在另一个维度中为正弦

这样的事情:

        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";

        });