如何在移动时在画布上制作动画效果?

时间:2016-03-09 09:07:59

标签: javascript html5 css3 canvas duration

移动时是否可以在画布上制作动画效果? 我只需要在画布之间进行动画移动。位置

与css3类似:-webkit-transition-duration: 1s;

感谢任何帮助。

<html>
<head>
  <style>
      #myCanvas {
              -webkit-transition-duration: 1s;
      }
</style>
  <title>JS Bin</title>
</head>
<body>
        <canvas id="myCanvas" width="1280" height="600" style="border:1px solid #d3d3d3;color:red;"></canvas>
    <script>   
      var c = document.getElementById("myCanvas");
      var ctx = c.getContext("2d");
      var w = document.getElementById("myCanvas");
      timer = setInterval(function() { 

            var f = Math.floor(1+Math.random()*680);
            var f2 = Math.floor(1+Math.random()*400);
          console.log (f, f2);

            ctx.fillStyle="#FF0000";
            ctx.clearRect(0, 0, c.width, c.height);
            ctx.fillRect(f, f2, 100, 50); 
            w.onclick = function() {
                clearInterval(timer);
                falling();
            } 
         }, 300 //the seconds of interval movement)
        function falling(){
            ctx.clearRect(0,0,c.width,c.height);
            ctx.fillRect(500,500,100,50)

        }              
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

不确定。如果您只想计算从起点到终点的一条线的临时位置,那么您可以这样做:

non-functioning "iterative" version:
<div class="rel">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>
<br /><br />
Functioning individual-rules version (what I want):
<div class="rel">
    <div class="item i2"></div>
    <div class="item i2"></div>
    <div class="item i2"></div>
    <div class="item i2"></div>
    <div class="item i2"></div>
</div>

如果你想用天赋制作动画,那么你可以使用Robert Penner的easing functions以非线性的方式制作动画。

要为动画添加固定的持续时间,您可以根据以下内容计算percentComplete:

// percentComplete is a number between 0.00 and 1.00
// representing the current progress of the animation from start to end
var x = startingX+(endingX-startingX)*percentComplete;
var y = startingY+(endingY-startingY)*percentComplete;