javascript - 不同对象的方法无法同时执行(D3.js)

标签 javascript sorting d3.js

JavaScript 新手,我正在尝试 d3.js。我想创建一个网站来直观地比较不同的排序算法。基本上,我修改了排序算法以具有“displayArray”(一个二维数组,是排序算法循环的每次迭代的快照)。然后我遍历该循环,并在每次迭代的 d3 中创建一个条形图 结果看起来类似于著名的 Sounds of Sorting 。但是,我在同时运行动画功能时遇到问题。看起来,如果两个动画同时进行,它们会发生在同一个 div 中,而不是它们自己单独的指定容器。我已经使用 Frankenstein method of combining jQuery and D3 完成了此操作,但我尝试仅使用 D3 来制作动画。任何帮助和建议表示赞赏。谢谢你!

var w = 100;
var h = 100;
var barPadding = 0.2;

function graphObject(container, dataComp, algorithm) {
  _this = this;
  this.container = container;
  this.createDataSet = function() {
    var arry = [];
    for (var i = 0; i < 50; i++) {
      arry[i] = i + 1;
    }
    if (dataComp == 'random') {
      shuffle(arry);
      return arry
    } else if (dataComp == 'reverse') {
      arry.reverse();
      return arry

    }
  };
  this.dataSet = this.createDataSet();
  this.createInitalGraph = function() {
    _this = this;
    var svg = d3.select(container)
      .append('svg')
      .attr('width', w + '%')
      .attr('height', h + '%');

    svg.selectAll('rect')
      .data(this.dataSet)
      .enter()
      .append('rect')
      .attr('x', function(d, i) {
        return (i * (w / _this.dataSet.length)) + '%';
      })
      .attr('y', function(d) {
        return h - d * (100 / _this.dataSet.length) + '%';
      })
      .attr('width', (w / _this.dataSet.length - barPadding) + '%')
      .attr('height', function(d) {
        return d * (100 / _this.dataSet.length) + '%';
      })
      .attr('fill', function(d) {
        return '#ffffff';
      });
    svg.exit().remove();
  };

  this.animate = function() {
    _this = this
    frameArray = [];
    if (algorithm == 'bubbleSort') {
      frameArray = bubbleSort(this.dataSet);
    } else if (algorithm == 'selectionSort') {
      frameArray = selectionSort(this.dataSet);
    } else if (algorithm == 'cocktailSort') {
      frameArray = cocktailSort(this.dataSet);
    }
    for (var j = 1; j < frameArray.length; j++) {
      (function(j) {
        setTimeout(function() {
          _this.updateGraph(frameArray[j], frameArray[j - 1])
        }, j * 30);
      })(j);

    }
  };
  this.updateGraph = function(data, prevData) {
    var bars = d3.select(container)
      .select('svg')
      .selectAll('rect')
      .data(data);
    bars.enter()
      .append('rect');
    bars.attr('x', function(d, i) {
        return (i * (w / data.length)) + '%';
      })
      .attr('y', function(d) {
        return h - d * (100 / data.length) + '%';
      })
      .attr('width', (w / data.length - barPadding) + '%')
      .attr('height', function(d) {
        return d * (100 / data.length) + '%';
      })
      .attr('fill', function(d, i) {
        if (data[i] != prevData[i]) {
          return 'red';
        } else {
          return 'white';
        }
      });
    bars.exit().remove();
  };
}

function bubbleSort(items) {
  var displayArray = [],
    swapped,
    temp;
  do {
    swapped = false;
    for (var i = 0; i < items.length; i++) {
      displayArray.push(items.slice());
      if (items[i] > items[i + 1]) {
        temp = items[i];
        items[i] = items[i + 1];
        items[i + 1] = temp;
        swapped = true;
      }
    }
  } while (swapped);
  return displayArray;
}

function selectionSort(items) {
  var len = items.length,
    min,
    temp,
    displayArray = [];
  for (i = 0; i < len; i++) {
    min = i;
    for (j = i + 1; j < len; j++) {
      displayArray.push(items.slice());
      if (items[j] < items[min]) {
        min = j;
      }
    }
    if (i != min) {
      temp = items[i];
      items[i] = items[min];
      items[min] = temp;
    }
  }
  displayArray.push(items.slice());
  displayArray.push(items.slice());
  return displayArray;
}

function cocktailSort(items) {
  var swapped;
  var displayArray = [];
  var temp;
  do {
    for (var i = 0; i <= items.length - 2; i++) {
      displayArray.push(items.slice());
      if (items[i] > items[i + 1]) {
        temp = items[i];
        items[i] = items[i + 1];
        items[i + 1] = temp;
        swapped = true;
      }
    }
    if (!swapped) {
      break;
    }
    swapped = false;
    for (i = items.length - 2; i >= 0; i--) {
      displayArray.push(items.slice());
      if (items[i] > items[i + 1]) {
        temp = items[i];
        items[i] = items[i + 1];
        items[i + 1] = temp;
        swapped = true;
      }
    }
  } while (swapped);

  return displayArray;
}

function shuffle(array) {
  var currentIndex = array.length,
    temporaryValue, randomIndex;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  return array;
}

var graph1 = new graphObject('.graphContainer1', 'random', 'bubbleSort');
var graph2 = new graphObject('.graphContainer2', 'random', 'selectionSort');
var graph3 = new graphObject('.graphContainer3', 'random', 'cocktailSort');

graph1.createInitalGraph();
graph2.createInitalGraph();
graph3.createInitalGraph();

$(".BubbleSort").click(function() {
  graph1.animate();
});

$(".SelectionSort").click(function() {
  graph2.animate();
  console.log(graph1.container);
});

$(".CocktailSort").click(function() {
  graph3.animate();
});
html {
  background: black;
}

p {
  color: white;
}

.graph {
  width: 300px;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="BubbleSort">BubbleSort</button>
<button class="SelectionSort">Selection Sort</button>
<button class="CocktailSort">Cocktail Sort</button>
<p>Bubble Sort </p>
<div class="graph graphContainer1">
</div>
<p>Selection Sort </p>
<div class="graph graphContainer2">
</div>
<p>Cocktail Sort </p>
<div class="graph graphContainer3">
</div>

额外问题:如何使用 window.requestAnimationFrame 而不是 setTimeOut 来完成此动画?

最佳答案

问题在于您的 _thisframeArray 变量是全局变量,因为它们当前已被赋值,而从未使用 var 进行声明。使用 var 将它们设为本地。

此外,您不需要在每个实例方法中定义 _this,因为这些方法已经在您的 graphObject() 函数的范围内,因此可以只使用该函数第一行定义的_this

var w = 100;
var h = 100;
var barPadding = 0.2;

function graphObject(container, dataComp, algorithm) {
  var _this = this;      // <---- Add 'var' here
  this.container = container;
  this.createDataSet = function() {
    var arry = [];
    for (var i = 0; i < 50; i++) {
      arry[i] = i + 1;
    }
    if (dataComp == 'random') {
      shuffle(arry);
      return arry
    } else if (dataComp == 'reverse') {
      arry.reverse();
      return arry

    }
  };
  this.dataSet = this.createDataSet();
  this.createInitalGraph = function() {
    //  _this = this; <-- remove this line
    var svg = d3.select(container)
      .append('svg')
      .attr('width', w + '%')
      .attr('height', h + '%');

    svg.selectAll('rect')
      .data(this.dataSet)
      .enter()
      .append('rect')
      .attr('x', function(d, i) {
        return (i * (w / _this.dataSet.length)) + '%';
      })
      .attr('y', function(d) {
        return h - d * (100 / _this.dataSet.length) + '%';
      })
      .attr('width', (w / _this.dataSet.length - barPadding) + '%')
      .attr('height', function(d) {
        return d * (100 / _this.dataSet.length) + '%';
      })
      .attr('fill', function(d) {
        return '#ffffff';
      });
    svg.exit().remove();
  };

  this.animate = function() {
    //  _this = this; <-- remove this line
    var frameArray = [];      // <---- Add 'var' here
    if (algorithm == 'bubbleSort') {
      frameArray = bubbleSort(this.dataSet);
    } else if (algorithm == 'selectionSort') {
      frameArray = selectionSort(this.dataSet);
    } else if (algorithm == 'cocktailSort') {
      frameArray = cocktailSort(this.dataSet);
    }
    for (var j = 1; j < frameArray.length; j++) {
      (function(j) {
        setTimeout(function() {
          _this.updateGraph(frameArray[j], frameArray[j - 1])
        }, j * 30);
      })(j);

    }
  };
  this.updateGraph = function(data, prevData) {
    var bars = d3.select(container)
      .select('svg')
      .selectAll('rect')
      .data(data);
    bars.enter()
      .append('rect');
    bars.attr('x', function(d, i) {
        return (i * (w / data.length)) + '%';
      })
      .attr('y', function(d) {
        return h - d * (100 / data.length) + '%';
      })
      .attr('width', (w / data.length - barPadding) + '%')
      .attr('height', function(d) {
        return d * (100 / data.length) + '%';
      })
      .attr('fill', function(d, i) {
        if (data[i] != prevData[i]) {
          return 'red';
        } else {
          return 'white';
        }
      });
    bars.exit().remove();
  };
}

function bubbleSort(items) {
  var displayArray = [],
    swapped,
    temp;
  do {
    swapped = false;
    for (var i = 0; i < items.length; i++) {
      displayArray.push(items.slice());
      if (items[i] > items[i + 1]) {
        temp = items[i];
        items[i] = items[i + 1];
        items[i + 1] = temp;
        swapped = true;
      }
    }
  } while (swapped);
  return displayArray;
}

function selectionSort(items) {
  var len = items.length,
    min,
    temp,
    displayArray = [];
  for (i = 0; i < len; i++) {
    min = i;
    for (j = i + 1; j < len; j++) {
      displayArray.push(items.slice());
      if (items[j] < items[min]) {
        min = j;
      }
    }
    if (i != min) {
      temp = items[i];
      items[i] = items[min];
      items[min] = temp;
    }
  }
  displayArray.push(items.slice());
  displayArray.push(items.slice());
  return displayArray;
}

function cocktailSort(items) {
  var swapped;
  var displayArray = [];
  var temp;
  do {
    for (var i = 0; i <= items.length - 2; i++) {
      displayArray.push(items.slice());
      if (items[i] > items[i + 1]) {
        temp = items[i];
        items[i] = items[i + 1];
        items[i + 1] = temp;
        swapped = true;
      }
    }
    if (!swapped) {
      break;
    }
    swapped = false;
    for (i = items.length - 2; i >= 0; i--) {
      displayArray.push(items.slice());
      if (items[i] > items[i + 1]) {
        temp = items[i];
        items[i] = items[i + 1];
        items[i + 1] = temp;
        swapped = true;
      }
    }
  } while (swapped);

  return displayArray;
}

function shuffle(array) {
  var currentIndex = array.length,
    temporaryValue, randomIndex;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  return array;
}

var graph1 = new graphObject('.graphContainer1', 'random', 'bubbleSort');
var graph2 = new graphObject('.graphContainer2', 'random', 'selectionSort');
var graph3 = new graphObject('.graphContainer3', 'random', 'cocktailSort');

graph1.createInitalGraph();
graph2.createInitalGraph();
graph3.createInitalGraph();

$(".BubbleSort").click(function() {
  graph1.animate();
});

$(".SelectionSort").click(function() {
  graph2.animate();
  console.log(graph1.container);
});

$(".CocktailSort").click(function() {
  graph3.animate();
});
html { background: black; }
p { color: white; }
.graph { width: 300px;}
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="BubbleSort">BubbleSort</button>
<button class="SelectionSort">Selection Sort</button>
<button class="CocktailSort">Cocktail Sort</button>
<p>Bubble Sort </p>
<div class="graph graphContainer1">
</div>
<p>Selection Sort </p>
<div class="graph graphContainer2">
</div>
<p>Cocktail Sort </p>
<div class="graph graphContainer3">
</div>

关于javascript - 不同对象的方法无法同时执行(D3.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45428710/

相关文章:

javascript - 在js.class中,是否可以调用父类的其他函数

JavaScript:在函数内部定义函数

javascript - 如何在 iOS Titanium 中创建复选框?

javascript - 隐藏字段占用空间

algorithm - 查找最近和最近的帖子,限制 20

Python - 根据第一个单词对文件中的行进行排序?

c - 使用双指针对字符串中的字母进行排序

javascript - 绘制多条实时线

javascript - 如何在 D3.js 中不使用 .on() 来获取组元素内圆的位置?

javascript - 使用 d3 通过投影映射 geojson 分布数据