繁体   English   中英

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

[英]How do I create n canvases from within Javascript?

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

    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的要点总是等同于我,所以为什么不仅仅使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM