简体   繁体   English

HTML Canvas Animate折叠三角形

[英]HTML Canvas Animate folding triangle

I have drawn a triangle with canvas, 我用帆布画了一个三角形,

http://jsfiddle.net/nicekiwi/GfM6M/ http://jsfiddle.net/nicekiwi/GfM6M/

I want to animate the triangle "unfolding" by moving one corner of it away form the other 2. 我想通过将三角形的一个角移开另一个2来为三角形“展开”设置动画。

o---o---o 

animate to below over 0.8 seconds or something. 动画到0.8秒以下。

    o    
   / \
  /   \
 /     \
o-------o

How can I do this? 我怎样才能做到这一点? All the tutorials I could find move the entire object not a single point of it. 我能找到的所有教程都不会移动整个对象。

I really want to animate a number of these opening form each other in sequence, but hopefully I can figure that out myself. 我真的很想依次对这些开口进行动画处理,但希望我能自己弄清楚。 :) :)

When you want to animate a canvas, you need to create the animation in frames. 要为画布设置动画时,需要按帧创建动画。 Draw one frame, erase the canvas, and draw the next. 绘制一帧,擦除画布,然后绘制下一帧。

To get the timing right, you can use setInterval to execute a function at regular intervals. 为了获得正确的时间,可以使用setInterval定期执行一个函数。 In the function you pass to setInterval: 在函数中,您传递给setInterval:

  1. erase the canvas with context.clearRect 使用context.clearRect擦除画布
  2. adjust the coordinates 调整坐标
  3. draw a triangle with the new coordinates 用新坐标画一个三角形

Adding this code below yours does the trick: 将此代码添加到您的代码下面即可达到目的:

var x = 300;

// execute a function every 50ms
window.setInterval( function() {
    // erase the canvas
    var context = document.getElementById('canvas').getContext('2d');
    context.clearRect(0, 0, 900, 500);
    // update the coordinates
    x++;
    if (x > 500) x = 300;
    // redraw with new coordinates
    draw_triangle('410','48',x,'86','420','135');
}, 50);

A more professional way would be to use requestAnimationFrame instead of setInterval which has many advantages. 一种更专业的方法是使用requestAnimationFrame而不是setInterval,它具有很多优点。 But it makes your programming more complicated, because the animation speed will depend on the framerate and you either will need to compensate for that or decouple logic from rendering. 但这会使您的编程更加复杂,因为动画速度将取决于帧速率,并且您将需要对此进行补偿或将逻辑与渲染分离。

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

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