Gannys
Gannys

Reputation: 33

How to chage the color of shapes with easeljs

function initCircles() {
  circles = [];
  for (var i = 0; i < 100; i++) {
    var circle = new createjs.Shape();
    var r = 7;
    var x = window.innerWidth * Math.random();
    var y = window.innerHeight * Math.random();
    var color = colors[Math.floor(i % colors.length)];
    var alpha = 0.2 + Math.random() * 0.5;
    circle.alpha = alpha;
    circle.radius = r;
    circle.graphics.beginFill(color).drawCircle(0, 0, r);
    circle.x = x;
    circle.y = y;
    circles.push(circle);
    circle.movement = 'float';

    circle.addEventListener("mouseover", function(event) {
      circle.graphics.clear().beginFill("red").drawRect(0, 0, 50, 60).endFill();
      stage.update(event);
    });

    stage.addChild(circle);

  }
}

I'm trying to add a mouseover listener on the little circles I create on the page, I hope that once I place the cursor on the circle, it becomes a rectangle. However, the rectangle always appear where some other circle exists rather than the circle I point to.

Upvotes: 1

Views: 637

Answers (2)

Lanny
Lanny

Reputation: 11294

Save your beginFill command, and change it later:

// your other code above
var fillCmd = circle.graphics.beginFill(color).command; // Note the .command at the end
circle.graphics.drawCircle(0, 0, r);
// your other code below

// Later
fillCmd.style = "ff0000";

Here is an article about it, and here are the docs - Admittedly, this could be documented better. :)

Upvotes: 1

mmso
mmso

Reputation: 71

The problem is that you are referencing a mutable variable inside of the closure. There are a couple of ways to solve that.

1) Either somehow reference the circle from the event variable inside of the nested function (if the event has support for that), or

2) Bind the value of the variable inside another function, e.g:

function initCircles() {
    circles = [];
    for (var i = 0; i < 100; i++) {
        var circle = new createjs.Shape();
        var r = 7;
        var x = window.innerWidth * Math.random();
        var y = window.innerHeight * Math.random();
        var color = colors[Math.floor(i % colors.length)];
        var alpha = 0.2 + Math.random() * 0.5;
        circle.alpha = alpha;
        circle.radius = r;
        circle.graphics.beginFill(color).drawCircle(0, 0, r);
        circle.x = x;
        circle.y = y;
        circles.push(circle);
        circle.movement = 'float';

        addEventListener(circle);

        stage.addChild(circle);
    }
    function addEventListener(circle) {
        circle.addEventListener("mouseover", function(event) {
            circle.graphics.clear().beginFill("red").drawRect(0, 0, 50, 60).endFill();
            stage.update(event);
        });
    }
}

Upvotes: 0

Related Questions