Best way to make an image follow a circular path in JQuery?

邮差的信 提交于 2019-12-20 05:45:10

问题


I have an image (red, below), that I want to make travel along a circular path. The red image should always end in the same spot as it started.

Notes: The grey circular path is invisible. I am just highlighting the path it will follow.

What is the best method/library to achieve this technique?


回答1:


Do you really need a library, it's not that hard to do

$(document).ready(function (e) {
    var startAngle = 0;
    var unit = 215;

    var animate = function () {
        var rad = startAngle * (Math.PI / 180);
        $('.circle').css({
            left: 250 + Math.cos(rad) * unit + 'px',
            top: unit * (1 - Math.sin(rad)) + 'px'
        });
        startAngle--;
    }
    var timer = setInterval(animate, 10);
});

FIDDLE

Here's one that does one loop, stops at the same place etc.

$(document).ready(function (e) {
    var startAngle = 180;
    var unit = 215;

    var animate = function () {
        if (startAngle > -180) {
            var rad = startAngle * (Math.PI / 180);
            $('.circle').css({
                left: 250 + Math.cos(rad) * unit + 'px',
                top: unit * (1 - Math.sin(rad)) + 'px'
            });
            startAngle--;
            setTimeout(animate, 10);
        }
    }

    $('.circle').on('click', function() {
        startAngle = 180;
        animate();
    });

});

FIDDLE




回答2:


Please look into these links:

  • CSS Technique
  • Stackoverflow Answers : Answer 1 || Answer 2
  • JSFiddle : Fiddle 1

     var t = 0;
    
     function moveit() {
       t += 0.05;
    
       var r = 100;
       var xcenter = 100;
       var ycenter = 100;
       var newLeft = Math.floor(xcenter + (r * Math.cos(t)));
       var newTop = Math.floor(ycenter + (r * Math.sin(t)));
       $('#friends').animate({
         top: newTop,
         left: newLeft,
       }, 1, function() {
       moveit();
      });
     }
    
     $(document).ready(function() {
        moveit();
     });
    


来源:https://stackoverflow.com/questions/20967790/best-way-to-make-an-image-follow-a-circular-path-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!