Create dynamic Two.js variables to involve individ

2019-07-28 04:14发布

In creating a two.js object, here are the parts:

var circle1 = two.makeCircle(676,326,25);
circle1.noStroke().fill = getRandomColor();
circle1.domElement = document.querySelector('#two-' + circle1.id);
$(circle1.domElement)
    .css('cursor', 'pointer')
    .click(function(e) {
        circle1.fill = getNonMainRandomColor(getRandomColor());
    });

I tried to save all the necessary parameters in an array as such:

[x position, y position, radius, color]

So I have the function

function showCircles(array) {
  for(var i = 0; i < array.length; i++) {
    var rotato = two.makeCircle(array[i][0],array[i][1],array[i][2]);
    rotato.noStroke().fill = array[i][3];
    rotato.domElement = document.querySelector('#two-' + rotato.id);
    $(rotato.domElement).css('cursor', 'pointer').click(function(e) {rotato.fill = getNonMainRandomColor(getRandomColor());});
  } 
}

The problem with the latter is that the lines

    rotato.domElement = document.querySelector('#two-' + rotato.id);
    $(rotato.domElement).css('cursor', 'pointer').click(function(e) {rotato.fill = getNonMainRandomColor(getRandomColor());});

require a fresh variable every time it is fired thus the output is a group of circles that when clicked individually, only the last one changes color because of the setting that I have which is caused by var rotato that should be new every circle and iteration.

How do I make the variable dynamic or is there a better solution to this mess?

Here is a codepen fork.

1条回答
Melony?
2楼-- · 2019-07-28 05:09

The issue here is that JavaScript's for statement doesn't create closures for each iteration. As a result when any of the circles is clicked it looks for what the reference to rotato. This variable is reused for each iteration and the result is what you're referring to as the last item in the array.

I've forked and made a new codepen that uses underscore.js's map method which is bundled in two.js. This is similar to a for statement except that for each iteration it creates a closure making independent references to each of the rotato variables you're constructing.

http://codepen.io/anon/pen/ylzvx

查看更多
登录 后发表回答