AL-zami
AL-zami

Reputation: 9066

bitmaplist[i] is undefined

the code here draw 5 grass image on the canvas on random places.i gave all the grass objects an unique name.Then i made a click event for every grass objecs which will show their individual names.

 bitmaplist[i].on('click',function vanish(event){

alert(bitmaplist[i].name);

 }
  );

but it keeps giving me error that bitmaplist[i] is undefined.what might be the reason for this problem and how it can be fixed?

FULL CODE:

<html>
<head>
<script src="easeljs.js"></script>
</head>
<body>
<canvas id="mycanvas" width="1000" height="500" style="border:1px solid black;"></canvas>
<script>
function makeit(){
  var bitmaplist=[];
  var i;
  var canvas=document.getElementById("mycanvas");
  var ctx=canvas.getContext('2d');
  var stage=new createjs.Stage(canvas);
  var image=new Image();
  image.src="grass.jpg";


  for(i=0;i<5;i++){
   bitmaplist[i]=new createjs.Bitmap(image);


     bitmaplist[i].x=stage.canvas.width-Math.random()*900;
  bitmaplist[i].y=Math.random()*400;
  bitmaplist[i].name="grass"+i;
  bitmaplist[i].speed=Math.random()*5;
  bitmaplist[i].mouseEnabled=true;

  stage.addChild(bitmaplist[i]);
  stage.update();
    bitmaplist[i].on('click',function vanish(event){

alert(bitmaplist[i].name);

 }
  );
  }



}
window.onload=makeit;
</script>
</body>
</html>

Upvotes: 0

Views: 50

Answers (1)

DominikStyp
DominikStyp

Reputation: 370

Try this object:

bitmaplist[i].on('click',function vanish(event){
   alert(this.name);
});

Or using target property of Event object:

bitmaplist[i].on('click',function vanish(event){
   alert(event.target.name);
});

Read more here EventDispatcher

Upvotes: 2

Related Questions