我如何从Javascript内创建n画布

How do I create n canvases from within Javascript?

本文关键字:创建 画布 Javascript      更新时间:2023-09-26

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

    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);
    }

for循环:

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

在第一次执行时只运行一次j == upperBound。要解决这个问题,请删除

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

和upperBound的意义是什么呢反正它总是等于i所以为什么不直接用呢