javascript - 如何在移动时在 Canvas 上制作动画效果?

标签 javascript html css canvas duration

是否可以边移动边在 Canvas 上做动画效果? 我只需要在 Canvas 的位置之间进行动画移动,

如在 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>

最佳答案

当然。如果您只想计算从起点到终点沿直线的临时位置,那么您可以这样做:

// 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;

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

要为动画添加固定持续时间,您可以根据以下公式计算完成百分比:

var percentComplete = elapsedTime / animationDuration;

关于javascript - 如何在移动时在 Canvas 上制作动画效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35887191/

相关文章:

html - 在 Bootstrap 中导入 modal.less

javascript - 元素的绝对布局将溢出但仅在 3 边受限

html - 如何删除 HTML 电子邮件中的链接下划线?

html - 创建具有不同子类型的自定义元素

javascript - Express:下载返回空文件

javascript - node.js 中的计算属性

javascript - Angular js 无法识别 Controller

javascript - 嵌套 DOM 生成错误

javascript - 重新加载没有 &lt;script&gt; 标签的页面

html - 使用 CSS 3 使列表中的元素右对齐