【问题标题】:Nested animations using canvas and javascript使用画布和 JavaScript 的嵌套动画
【发布时间】:2011-07-25 15:14:09
【问题描述】:

是否可以使用 canvas 和 javascript 制作嵌套动画?例如,一只蝴蝶扇动翅膀,同时沿着一条路径移动。

制作这种动画的最佳方式是什么?同一只蝴蝶将有多个实例朝不同的方向移动。

现在我正在画布上绘制蝴蝶形状,分为左右两部分,我将分别制作动画。然后我会在一条路径上为整个蝴蝶设置动画。

似乎在多个绘图和动画上会使用很多处理,这可以通过使用 PNG 而不是形状甚至是动画 GIF 来保存吗?

任何建议将不胜感激!谢谢!

【问题讨论】:

    标签: javascript html animation canvas


    【解决方案1】:

    回答您的第一个问题:是的,它们是可能的。要回答您的第二个问题:一种“最佳”方式是在画布上下文中使用任意嵌套的转换。

    我创建了一个示例,展示了如何在不知道当前转换是什么的情况下在上下文中发出绘图命令,然后将这些命令包装在为结果设置动画的转换中。

    在此处查看结果:http://phrogz.net/tmp/canvas_nested_animations.html

    以下是该方法的基本概述:

    // Draw a bug with animated legs
    function drawBug(){
      ctx.save();
      // Issue drawing commands, assuming some 0,0 center and an unrotated bug
      // Use the current time, or some frame counter, to change how things are drawn
      ctx.restore();
    }
    
    // Move the (animated) bug around
    function drawMovingBug(){
      ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
    
      ctx.save();
      // Adjust the bug's location/rotation based on some animation path
      // and the current time or frame counter.
      var bugPosition = findCurrentBugPosition();
      ctx.rotate(bugPosition.angle);
      ctx.translate(bugPosition.x,bugPosition.y);
    
      // Draw the bug using the new transformation
      drawBug();          
      ctx.restore();
    }
    

    【讨论】:

    • 是的,使用内置的转换堆栈是要走的路。
    • 非常感谢,正是我想知道的!我会试一试! :D
    • @Phrogz,我可以将 translate 命令放在 drawMovingBug 方法中,然后将 rotate 命令放在后面吗?这样做会达到和以前一样的效果。
    • @rajkamal 试试看!自我探索比问答更能教你。
    • 发现它们不一样。放了一个小提琴jsfiddle.net/Fcd7Y。如果我在旋转后平移.. 物体相对于倾斜轴平移。如果我之前平移,旋转,对象在法线轴上移动。我在小提琴中使用了你的图像。请。让我知道它是否冒犯了你。
    猜你喜欢
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2018-08-13
    相关资源
    最近更新 更多