简体   繁体   English

使用画布沿弯曲运动路径进行动画处理

[英]Animating Along Curved Motion Path Using Canvas

I'm currently trying to do a bit of an experiment with Canvas, it's one of my first forays into using it. 我目前正在尝试对Canvas进行一些实验,这是我第一次尝试使用Canvas。 The linked CodePen is some brilliant code from another user that I've forked to create something in the style I needed. 链接的CodePen是来自另一个用户的出色代码,我分叉来创建所需样式的东西。

http://codepen.io/anon/pen/utgvb http://codepen.io/anon/pen/utgvb

The functionality I'm trying to create is that of the line animating in a loop until a mousemove within the canvas element. 我正在尝试创建的功能是循环动画的线条, 直到在canvas元素内移动鼠标为止 My thoughts were to use Math.random() to generate numbers for each x and y co-ordinate but I'm having trouble figuring out the logic. 我的想法是使用Math.random()为每个x和y坐标生成数字,但是我很难弄清楚逻辑。 I want to make it as graceful and code-light as possible which means utilising much of the existing code - however only having a 70% accurate grasp of how the code is running is hampering my progress. 我想使它尽可能优美和代码轻巧,这意味着要利用现有的许多代码-但是,仅对代码的运行方式只有70%的准确把握会妨碍我的进步。

I thought a function that works similar to this one that's already in use could be created: 我认为可以创建一个与已经使用的功能相似的功能:

function update() {

  target.x += (mouse.x - target.x);
  target.y += (mouse.y - target.y);

  chain.update( target );
}

I believe this function is key to making the line follow the cursor, so my thinking was to create a function that accessed the properties of an array of objects, each containing "x: foo, y: bar" in a loop, thus moving the line to those co-ordinates one after the other. 我认为该函数是使行跟随光标移动的关键,因此我的想法是创建一个函数,该函数访问循环包含“ x:foo,y:bar”的对象数组的属性,从而移动一条线接另一条线。 I have a feeling however, there may be a far simpler solution staring me in the face. 但是我有一种感觉,也许有一个更简单的解决方案盯着我。

Does any one have any pointers? 有人有指针吗?

Just for transparency I'll post the code I added to create the animation, with thanks to nepeo for the advice: 为了透明起见,我将发布为创建动画添加的代码,感谢nepeo的建议:

function animLoop() {

  var speed = 5,    
      rad = (degree * Math.PI / 180);

  degree += 1;  

  mouse.x += speed * Math.sin(rad);
  mouse.y += speed * Math.cos(rad);

  //reset degrees
  if (degree == 360) {
      degree = 0;
  }
}

If anyone needs more info on animating along curves in Canvas I recommend starting here: 如果有人需要更多有关在Canvas中沿曲线设置动画的信息,建议从这里开始:

http://chimera.labs.oreilly.com/books/1234000001654/ch05.html#uniform_circular_motion http://chimera.labs.oreilly.com/books/1234000001654/ch05.html#uniform_circular_motion

It's really comprehensive and helps you understand exactly what it is you're doing with the mathematics rather than just giving you the solution. 它确实很全面,可以帮助您确切地了解您在用数学做什么,而不仅仅是提供解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM