使用canvas和javascript嵌套动画

iam*_*all 5 javascript html5 animation canvas

嵌套动画是否可以使用canvas和javascript?例如,一只蝴蝶拍打它的翅膀,同时沿着一条小路移动.

创建这种动画的最佳方法是什么?将有多个相同蝴蝶在不同方向上移动的实例.

当我在画布上绘制蝴蝶形状时,分为两部分,左翼和右翼,我将分别制作动画.然后我会在一条小路上为整只蝴蝶设置动画.

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

任何意见,将不胜感激!谢谢!

Phr*_*ogz 6

回答你的第一个问题:是的,它们是可能的.回答你的第二个问题:一种"最好"的方法是在画布上下文中使用任意的转换嵌套.

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

请在此处查看结果: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();
}
Run Code Online (Sandbox Code Playgroud)