【问题标题】:Create smooth animation in canvas在画布中创建流畅的动画
【发布时间】:2019-07-23 13:25:55
【问题描述】:

我有一个正在渲染图像的画布对象。当用户单击按钮时,图像将向右移动。我的问题是这个动作不顺畅。图像只是跳转到指定位置。我怎样才能使这个动作平滑? This is the codepen example谁能帮帮我?

 $(window).on('load', function () {
            myCanvas();
        });

        function myCanvas() {
            var c = document.getElementById("myCanvas");
            var ctx = c.getContext("2d");
            var x = 0;

            function fly() {

                ctx.clearRect(0, 0, c.width, c.height);
                ctx.closePath();
                ctx.beginPath();

                var img = new Image();
                img.onload = function () {
                    ctx.drawImage(img, x, 0);
                };
                img.src = 'http://via.placeholder.com/200x200?text=first';
            }

            fly();

            $('#movebutton').click(function () {
                for (i = 0; i < 200; i++) {
                    x = i;
                    requestAnimationFrame(fly);
                }
            });

        }
 <canvas id="myCanvas" width="960" height="600"></canvas>
    <button id="movebutton">Move</button>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

【问题讨论】:

  • 这是一个复杂的话题。您正在寻找的东西称为“插值”。您必须考虑帧速率等。
  • 看来我需要对它进行彻底的研究......
  • 我花了很长时间研究,但是如果你没有时间并且可以使用它,我建议你这个 JS 库:createjs.com/easeljs
  • 我发现这个帖子很有帮助stackoverflow.com/questions/43626268/…

标签: javascript html animation canvas requestanimationframe


【解决方案1】:

首先,为什么要在帧渲染函数中加载图像 - 如果禁用缓存,它将每帧请求一个图像!

我重写了脚本,使动画线性平滑,你可以编辑速度变量来调整移动速度。

      $(window).on('load', function () {
        var img = new Image();
        img.onload = function () {
          myCanvas(img);
        };
        img.src = 'http://via.placeholder.com/200x200?text=first';

    });

    function myCanvas(img) {
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");
        var x = 0;
        var last_ts = -1
        var speed = 0.1

        function renderScene() {
            ctx.clearRect(0, 0, c.width, c.height);
            ctx.closePath();
            ctx.beginPath();
            ctx.drawImage(img, x, 0);             
        }

        function fly(ts) {
            if(last_ts > 0) {
              x += speed*(ts - last_ts)
            }
            last_ts = ts

            if(x < 200) {
              renderScene()
              requestAnimationFrame(fly);
            }
        }
        renderScene()
        $('#movebutton').click(function () {
          x = 0;
          requestAnimationFrame(fly);
        });

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    相关资源
    最近更新 更多