画布上的正方形在foor循环中只绘制一个正方形

时间:2016-08-21 18:44:41

标签: javascript html5 canvas

我使用canvas元素在黑色画布背景上绘制白色方块。

我在绘制黑色背景时没有任何困难,并且可以绘制一颗星,但是我在绘制多个白色方块时遇到困难。我很困惑,因为我在每个循环上绘制一个新的白色星形,但由于某种原因它不是绘制每个星形(白色方块)。

Based on this article I believe my code should work.

请参阅以下代码:

function Starfield () {
    this.ctx = document.getElementById('canvas');
    this.ctx = this.ctx.getContext("2d");
    this.stars = 2;
    this.createCanvas();
    this.createStar();
}

Starfield.prototype.createCanvas = function() {
    this.ctx.fillStyle = "#000";
    this.ctx.fillRect(0,0, window.innerHeight, window.innerWidth );
};

Starfield.prototype.createStar = function() {
    var rand1 = Math.random() * 50;
    var rand2 = Math.random() * 50;
    for (var i = 0; i < this.stars; i++) {
        this.ctx.fillStyle = "#fff";
        this.ctx.fillRect(rand1, rand2, 2, 2);
    };
};

1 个答案:

答案 0 :(得分:4)

尝试以下方法:

 public class CutrePool{
      String connString;    
      String user;
      String pwd;

      static final int INITIAL_CAPACITY = 50;
      LinkedList<Connection> pool = new LinkedList<Connection>();
      public String getConnString() {
          return connString;
      }
      public String getPwd() {
          return pwd;
      }

      public String getUser() {
          return user;
      }

      public CutrePool(String connString, String user, String pwd) throws SQLException {
          this.connString = connString;

          for (int i = 0; i < INITIAL_CAPACITY; i++) {
               pool.add(DriverManager.getConnection(connString, user, pwd));
          }
          this.user = user;
          this.pwd = pwd;
      }

      public synchronized Connection getConnection() throws SQLException {
          if (pool.isEmpty()) {
              pool.add(DriverManager.getConnection(connString, user, pwd));
          }
          return pool.pop();
      }

      public synchronized void returnConnection(Connection connection) {
          pool.push(connection);
      }  
  }

我将调用移到了循环内的conn = pool.getConnection();。您的代码只选择一个位置并在同一位置绘制所有星星(在彼此的顶部)。每颗星需要一个不同的随机位置。