【问题标题】:Why are my sparks not animating?为什么我的火花没有动画?
【发布时间】:2013-01-31 21:47:26
【问题描述】:

我在http://blajeny.com 有以下代码,用于在用户点击屏幕时设置几个火花的动画:

jQuery('body').click(function(event_object)
    {
    var number_of_sparks = 6 + Math.round(6 * Math.random());
    for(var index = 0; index < number_of_sparks; ++index)
        {
        spark(event_object.pageX, event_object.pageY);
        }
    });

function move_spark(image, angle, increment, speed, x, y)
    {
    console.log('angle: ' + angle + ', increment: ' + increment + ', speed: '
      + speed);
    my_angle = angle + (Math.random() - Math.random()) / 10;
    var velocity_x = Math.round(Math.cos(angle) * speed);
    var velocity_y = Math.round(Math.sin(angle) * speed);
    image.style.top = (y - 10 + velocity_y) + 'px';
    image.style.left = (x - 10 + velocity_x) + 'px';
    my_increment = increment + 1;
    if (increment > 10)
        {
        image.style.opacity = (20 - my_increment) / 10;
        }
    if (image.style.opacity < .01)
        {
        document.body.removeChild(image);
        }
    else
        {
        setTimeout(function()
            {
            move_spark(image, my_angle, my_increment, speed, x, y);
            }, 100);
        }
    }

function spark(x, y)
    {
    var increment = 0;
    var image_object = new Image();
    var angle = 2 * 3.1416 * Math.random();
    var speed = 7 * Math.random() + 7 * Math.random() + 7 * Math.random();
    image_object.onload = function()
        {
        image_object.style.position = 'absolute';
        image_object.style.zIndex = 1;
        image_object.style.top = (y - 10) + 'px';
        image_object.style.left = (x - 10) + 'px';
        }
    image_object.src = '/img/spark.png';
    document.body.appendChild(image_object);
    console.log('Before move_spark: ');
    move_spark(image_object, angle, increment, speed, x, y);
    }

如果我不运行动画,单击会在预期位置居中留下一个“火花标记”。但是,如果我尝试动画,我什么也看不到,并且日志似乎没有显示动画。目的是制作一个会移动两秒的动画,然后在第二秒内淡出到不可见。

如何纠正此代码?

【问题讨论】:

  • 什么火花,我看到的只是一些烦人的立方体?
  • @adeneo OP 说火花不会出现......或者你真的需要那些老花镜? ; )。
  • @Teemu - 哦,好吧,我真的需要眼镜。 +1 我至少努力访问该网站!
  • "in the second second" 哦,英语,你真傻。您如何在不单击的情况下启动动画?我只看到点击触发的东西。
  • @adeneo 请不要担心你的眼睛,我在那个页面上也看不到任何火花......只是浏览所有来源......

标签: javascript jquery css dom animation


【解决方案1】:

您没有设置不透明度,因此该对象从未出现在集合中

当您在此处检查不透明度时:

    if (image.style.opacity < .01) {
        document.body.removeChild(image);
    } else {
        setTimeout(function () {
            move_spark(image, my_angle, increment, speed, x, y);
        }, 100);
    }

它是空白而不是数字。

所以我通过向 image_object 添加不透明度来修复它。

Here is how it appears to be working, but I am not sure it is what you wanted.

我还对代码做了一些调整。你有一些多余的变量。

我不确定你的意思,但我认为this looks a little better

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    相关资源
    最近更新 更多