【问题标题】:Stuck with canvas/JS animation卡在画布/JS动画中
【发布时间】:2016-05-31 19:20:15
【问题描述】:

我正在开发一款在画布上玩的游戏,并希望使用 javascript 为背景层添加一些氛围。首先,这里是代码...

  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext("2d");
  var x = canvas.width/2;
  var y = canvas.height-150;
  var dx = Math.random() * (-5 * 5) + 15;
  var dy = -15;

  function drawDot() {
      ctx.beginPath();
      ctx.arc(x, y, 10, 0, Math.PI*2);
      ctx.fillStyle = "black";
      ctx.fill();
      ctx.closePath();
  };

  function move() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      drawDot();
      x += dx;
      y += dy;
  };
setInterval(move, 50);

如果你运行它,你会看到我所拥有的是一个黑球,它在一个随机的锥形空间内上下移动。我需要帮助的是找出最好的方法:
A. 用更多的球(可能像 2-3 个)填充它,这些球在它们自己的随机轨迹上,并且
B. 让这 2-3 个球在同一起始区域的页面外的随机锥形区域内不断动画(有点像不断喷水的喷泉效果)。

我已经看到的一个问题是,通过使用控制台日志,我现在拥有的 1 个工作球一直在画布外无限远,所以当我尝试添加一个新球时,它不会运行该功能.我对javascript非常陌生,尤其是canvas,如果这很明显,我深表歉意! 感谢您对此的任何帮助!

【问题讨论】:

    标签: javascript html animation canvas


    【解决方案1】:

    Seb Lee-Delisle 有一个关于这个确切问题的很好的教程:

    https://vimeo.com/36278748

    基本上你必须封装每个Dot,以便它知道自己的位置和加速度。

    编辑 1

    这是一个使用您自己的代码的示例:

    document.body.innerHTML = '<canvas height="600" width="600" id="myCanvas"></canvas>';
    clearInterval(interval);
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    var dotArray = [];
    
    function Dot() {
        var dot = {
            y : canvas.height / 2,
            x : canvas.width / 2,
            speedX : Math.random() * ( - 5 * 5) + 15,
            speedY : Math.random() * ( - 5 * 5) + 15,
            age : 0,
            draw : function () {
    
                this.x += this.speedX;
                this.y += this.speedY;
    
                ctx.beginPath();
                ctx.arc(this.x, this.y, 10, 0, Math.PI * 2);
                ctx.fillStyle = 'black';
                ctx.fill();
                ctx.closePath();
            }
        };
        return dot;
    }
    
    function draw() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        for (var i = 0; i < dotArray.length; i++) {
            dotArray[i].draw();
            dotArray[i].age++;
            if (dotArray[i].age > 20) {
                dotArray.splice(i, 1);
            }
        }
        dotArray.push(new Dot());
    }
    
    draw();
    var interval = setInterval(draw, 1000 / 60);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2018-12-16
      • 2012-12-21
      • 2017-08-06
      • 1970-01-01
      相关资源
      最近更新 更多