【问题标题】:How to add elements to a canvas that change over time?如何将元素添加到随时间变化的画布?
【发布时间】:2015-04-03 19:51:10
【问题描述】:

每当有人点击我网站的某些部分时,我想显示一个随着时间的推移而变大的圆圈。我想通过画布来做。到目前为止,我设法将圆圈添加到访问者点击的位置:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Canvas</title>
</head>
<body>
    <canvas id="myCanvas" width="500" height="500" style="border:1px solid #cccccc;">

    </canvas>
    <script src="bower_components/jquery/dist/jquery.min.js"></script>
    <script>

        /* Canvas test. */
        $(function() {
            var c = $("#myCanvas");
            // add element that changes over time,
            $(c).click(function(e) {
                var ctx = this.getContext("2d");
                ctx.beginPath();
                ctx.arc(e.pageX,e.pageY,40,0,2*Math.PI);
                ctx.stroke();
            });
        });

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

是否也可以让这些圆圈每 100 毫秒改变它们的半径 1px 并在它们的半径大于画布时消失?

没有画布也可以做到这一点吗?

【问题讨论】:

    标签: javascript jquery html canvas


    【解决方案1】:

    解决办法:

    您必须使用requestAnimationFrame,添加元素并随时间变化,将点推入数组,并绘制圆。

    /* Canvas test. */
    var circles = [];
    var canvas = null;
    var ctx = null;
    
    function loop() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    
      circles.forEach(function(arg) {
        var size = 100 - (new Date() - arg.time) / 10;
        if (size <= 0)
          return;
        ctx.beginPath();
        ctx.arc(arg.x, arg.y, size, 0, 2 * Math.PI);
        ctx.stroke();
      });
    
      requestAnimFrame(loop);
    }
    
    $(function() {
      canvas = $("#myCanvas")[0];
      ctx = canvas.getContext("2d");
    
      window.requestAnimFrame = (function() {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
          function(callback) {
            window.setTimeout(callback, 1000 / 60);
          };
      })();
    
      requestAnimFrame(loop);
    });
    
    
    $(function() {
      var c = $("#myCanvas");
      // add element that changes over time,
      $(c).click(function(e) {
        circles.push({
          time: +new Date(),
          x: e.pageX,
          y: e.pageY
        });
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <canvas id="myCanvas" width="500" height="500" style="border:1px solid #cccccc;"></canvas>

    【讨论】:

    • 离题了,但是,你用什么编码器来创建你的 .gif? :-)
    【解决方案2】:

    是否也可以让这些圆圈每 100 毫秒改变它们的半径 1px 并在它们的半径大于画布时消失?是的

    您可以启动动画循环(使用 raF)并更改/停止增长

    是否也可以在没有画布的情况下执行此操作?是的

    Javascript + SVG 或 javascript + css3 但这些可能不如 canvas 简单

    编辑:发现了一些其他有用的问题:Expanding circles with CSS3 animations

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-28
      • 2021-11-28
      • 2020-07-03
      • 2015-03-12
      相关资源
      最近更新 更多