如何在Javascript中创建n个画布?

时间:2014-08-03 17:28:50

标签: javascript html canvas innerhtml

我正在寻找一种方法来创建画布,因为我在运行时需要它们。到目前为止,我的代码是

    var isCanv = new Array();//bool array for which places in the arrays are/are not in use
    var canv = new Array();//for the canvases
    var ctx = new Array();//for the contexts
    var inhtml = new Array();//for the html canvas tags for each canvas
    var upperBound = -1;//the highest index used so far

    function createCtx(){
      var i = 0;
      while(isCanv[i]){
        i++;
      }
      inhtml[i] = '<canvas id="canv'+i+'" width="'+800+'px" height="'+800+'px" style="display:block;background:#ffffff+;"></canvas>';
      isCanv[i] = true;
      if(i>upperBound){
        upperBound = i;
      }
      var tohtml = '';
      for(var j = 0; j<= upperBound; j++){
        if(isCanv[i]){
          tohtml+=inhtml[j];
        }
      }
      document.getElementById('game').innerHTML=tohtml;
      canv[i] = document.getElementById('canv'+i);
      ctx[i] = canv[i].getContext('2d');
      return(i);
    }

    function keyEvent(event) {
      var i = 0;
      while(isCanv[i]){
        ctx[i].fillStyle="#00FFFF";
        ctx[i].fillRect(0,0,800,800);
        i++;
      }
    }

,html看起来像这样

    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>redicated</title>
      </head>
      <body style="background:#333333;" onkeydown="keyEvent(event)">
        <div id="game"></div>
        <script src="game.js"></script>
      </body>
    </html>

这适用于第一个画布,但任何后续添加都会破坏它。 有谁知道我怎么能解决这个问题,或者更好的方法呢?

编辑:

我明白了。每次添加时我都需要重新创建上下文。现在我的代码看起来像

    function createCtx(){
      var i = 0;
      while(isCanv[i]){
        i++;
      }
      inhtml[i] = '<canvas id="canv'+i+'" width="'+800+'px" height="'+800+'px" style="display:block;background:#ffffff+;"></canvas>';
      isCanv[i] = true;
      if(i>upperBound){
        upperBound = i;
      }
      var tohtml = '';
      for(var j = 0; j<= upperBound; j++){
        if(isCanv[j]){
          tohtml+=inhtml[j];
        }
      }
      document.getElementById('game').innerHTML=tohtml;
      for(var j = 0; j<= upperBound; j++){
        if(isCanv[j]){
          canv[j] = document.getElementById('canv'+j);
          ctx[j] = canv[j].getContext('2d');
        }
      }

      return(i);
    }

1 个答案:

答案 0 :(得分:0)

for循环:

 for(var j = 0; j<= upperBound; j++){
    if(isCanv[i]){
      tohtml+=inhtml[j];
 }

仅在首次执行时运行一次j == upperBound。要解决此问题,请尝试删除

  if(i>upperBound){
    upperBound = i;
  }

什么是upperBound,无论如何它总是等于我,所以为什么不用它呢。