Dynamic variable names with Javascript and constructor: cloning an image with EaselJS dynamically to multiple canvases

StackOverflow https://stackoverflow.com/questions/10114754

Вопрос

Good day! I'm here to ask help about dynamic variable names in Javascript applied to a constructor. It's been much more difficult than expected. I've read about this issue in numerous forums and webpages but I can't find what I'm doing wrong =/

I'm using a HTML5+Javascript library called EaselJS but my problem it's not related to it but to Javascript syntaxis! Here's my problem. I got this code:

stage1 = new Stage(document.getElementById("cnvs1"));
stage2 = new Stage(document.getElementById("cnvs2"));
stage3 = new Stage(document.getElementById("cnvs3"));

Here, the variables stage have assigned an Stage object which is initialized with canvas id cnvs This line (in the context of the rest of my code) works! I'd like to simplify this to a single line with a for like this:

for(i = 0; i < 5; i++){
  //Of course this is wrong!
  stage[i] = new Stage(document.getElementById("cnvs[i]"));
}

This link here resumes how this can be done: With eval (a lot of people say it's not recommendable) and with window (recommended) Then if I do this (without the for to simplify even more):

var varname = "stage";
var i = 1;
window[varname + i] = new Stage(document.getElementById("cnvs_terminal1"));

The code still works. But I can't figure out how to accomplish a similar solution with the canvas id in quotes. These lines of code fail:

var i = 1;
var varname = "stage";
var varname2 = 'cnvs1';
var varname3 = "\"cnvs1\"";
var varname4 = "\"cnvs1" + i + "\"";

window[varname +i] = new Stage(document.getElementById(window[varname2]));
window[varname +i] = new Stage(document.getElementById(window[varname3]));
window[varname +i] = new Stage(document.getElementById(window[varname4]));

In these attempts even trying to pass the exact value I need (without the i) it's not helping me!! I'm backslashing quotes because I think they are necessary for the getElementbyId=( =( =(

Now I'm clueless! =( I'm certain there is a way to do this, maybe I don't know the syntax, maybe I don't know how to call variables with reference or by value properly, I don't know... Please help me, I don't know how to do this simple task!

THANKS A LOT =)

EDIT: Trying @cHao suggestion I can't do it either! Keeping it simple, I set the for for i to be one only:

for (var i = 1; i <= 1; ++i) {
  //I use only one of the following lines at a time of course, but I'll write here my failing tries all together:
  stage[i] = new Stage(document.getElementById('cnvs'+i));
  stage[i-1] = new Stage(document.getElementById('cnvs'+i));

  //Hardcoding the first variable works!
  stage1 = new Stage(document.getElementById('cnvs'+i));
}

Half of the problem it's solved, but what to do with the first variable? =/ THANKS!!!!

EDIT 2: More detail has been requested! Here's a copy/paste example! Just update the EaselJS and an image paths for this to work!

<!DOCTYPE HTML>
<html>
  <head>
    <script src="easeljs-0.4.0-26/lib/easel.js"></script>       

    <script type="text/javascript"> 
      function init() {
        //MY PROBLEM LIES HERE!!
        for (var i = 1; i <= 1; ++i) {
          //This code WORKS
          stage1 = new Stage(document.getElementById('cnvs'+i));
          //This code DOES NOT WORKS
          //stage[i] = new Stage(document.getElementById('cnvs'+i));
          //stage[i-1] = new Stage(document.getElementById('cnvs'+i));
        }
        var images = "images/itzapic.jpg";
        bitmap = new Bitmap(images);
        stage1.addChild(bitmap);
        stage1.update();
        Ticker.addListener(window);
      }

      function tick() {
        stage1.update();
      }
    </script>        
  </head>

  <body onload="init()"> 
    <canvas id="cnvs1" width="140" height="82">
  </body>
</html>

___________________________________________

EDIT 3: SOLVED! I'll post the final code for reference to someone who want to use EaselJS to render a single image in as many canvases as needed with the same object. For this you'll need the bitmap.clone() method and arrays for the stages. Thanks to @cHao for helping me out ;) The following code will render the same image in all canvases! Update as necessary ;)

<!DOCTYPE HTML>
<html>
  <head>
    <script src="easeljs-0.4.0-26/lib/easel.js"></script>       

    <script type="text/javascript"> 
      stage = [];
      function init() {
        for (var i = 1; i <= 6; ++i) {
          stage[i-1] = new Stage(document.getElementById('cnvs'+i));
        }
        var images = "images/itzapic.jpg";
        bitmap = new Bitmap(images);
        stage[0].addChild(bitmap);
        for (var i = 1; i <= 5; ++i) {
          stage[i].addChild(bitmap.clone());
        }
        stage[0].update();
        Ticker.addListener(window);
        }

        function tick() {
        for (var i = 0; i < stage.length; ++i) {
          stage[i].update();
        }
      }
</script>        
</head>

  <body onload="init()"> 
    <canvas id="cnvs1" width="140" height="82"></canvas>
    <canvas id="cnvs2" width="140" height="82"></canvas>
    <canvas id="cnvs3" width="140" height="82"></canvas>
    <canvas id="cnvs4" width="140" height="82"></canvas>
    <canvas id="cnvs5" width="140" height="82"></canvas>
    <canvas id="cnvs6" width="140" height="82"></canvas>
  </body>
</html>
Это было полезно?

Решение

Not sure i get the point of eval'ing or pre-figuring variable names and all that. Seems like you could just do like

for (var i = 1; i <= 5; ++i) {
    stage[i] = new Stage(document.getElementById('cnvs' + i));
}

window["varname"] won't help unless varname is global, and...eh. You'll want to avoid globals if you can. Either way, you don't need to escape quotes -- you don't need quotes in the name itself at all unless your IDs have quotes in them (which, AFAIK is invalid anyway) or you're eval'ing (which is evil in itself).

If you're looking to put the stages into an array (which seems like a better goal), you'll want your first stage to be stage[0]. In which case, set stage[i-1] instead of stage[i].

And if you're trying to set stage1, stage2, etc...stop. Don't do that. You have a bunch of items, that you're treating alike...that's the kind of thing arrays were meant for. For one thing, notice how much easier it is to work with array elements than similarly-named variables? I wasn't even seeing the issue, because with arrays it's already a non-issue.

As for your code...watch this.

stage = [];

function init() {
    for (var i = 1; i <= 1; ++i) {
        stage[i-1] = new Stage(document.getElementById('cnvs'+i));
    }
    var images = "images/itzapic.jpg";
    bitmap = new Bitmap(images);
    stage[0].addChild(bitmap);
    stage[0].update();
    Ticker.addListener(window);
}

function tick() {
    for (var i = 0; i < stage.length; ++i) {
        stage[i].update();
    }
}

Once we switch from the stage1 stage2 brokenness to using an array, now we can have as many stages as we want.

Другие советы

I think you want this:

var stagePrefix = 'stage';
var canvasPrefix = 'cnvs';
//adjust loop below based on your naming e.g. do they start at 0 or 1?
for(var i=1;i<5;i++){
  window[stagePrefix + i] = new Stage(document.getElementById(canvasPrefix + i));
}

Rather than using an id with a numeric suffix to reference your canvases, I'd get them by tag name:

var canvases = document.getElementsByTagName("canvas");

Or, if you only want to process a certain set of the canvas elements on the page, give them a class:

var canvases = document.getElementsByClassName("cnvs");

Then, to get an Array of stages from your canvases, hijack the Array.map()* method:

var stages = [].map.call(canvases, function(canvas) {
    return new Stage(canvas);
});



*Array.map() is new to JS5, but if your browser supports <canvas> it supports JS5. Regardless, here's the link to an implementation of Array.map() you can use to support older browsers, in case you do have to support older browsers and you aren't already using a JS5 shim.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top