简体   繁体   中英

HTML Canvas Animate folding triangle

I have drawn a triangle with canvas,

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

I want to animate the triangle "unfolding" by moving one corner of it away form the other 2.

o---o---o 

animate to below over 0.8 seconds or something.

    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. In the function you pass to setInterval:

  1. erase the canvas with 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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