我想创建一个显示算法排序步骤的程序,如下所示:

https://visualgo.net/bn/sorting

https://www.youtube.com/watch?v=kPRA0W1kECg

现在,我不知道如何更改正在比较的矩形的颜色

例如,当array[i]array[i+1]比较时,我想更改这些颜色(绿色和红色...示例)



var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

var array = [10, 150, 17, 200, 300, 110, 400, 260, 105, 157, 180, 208, 400, 122, 40, 266, 123];

drawnLines(array);

function sleep(ts) {
  return new Promise((resolve, reject) => {
    return setTimeout(resolve, ts)
  })
}

async function init() {
  const it = bubbleSort(array)
  let result = it.next()

  while (!result.done) {
    ctx.clearRect(0, 0, 800, 500)
    drawnLines(array);
    result = it.next();
    await sleep(500)
  }
  console.log('finished!')
}

function drawnLines(array) {
  let height;
  let position = 5;

  ctx.font = "10px Verdana";

  for (i = 0; i < array.length; i++) {
    height = array[i];
    ctx.fillRect(position, 5, 20, height);
    ctx.strokeText(array[i].toString(), position, array[i] + 20);
    ctx.stroke();
    position += 48;
  }
};

function* bubbleSort(array) {
  var swapped;
  do {
    swapped = false;
    for (var i = 0; i < array.length - 1; i++) {
      if (array[i] > array[i + 1]) {
        var temp = array[i];
        array[i] = array[i + 1];
        array[i + 1] = temp;
        swapped = true;
        yield
      }
    }
  } while (swapped);
};

#myCanvas {
    border: 1px solid #000000;
    padding-left: 0;
    padding-right: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
    width: 800px;
}

.rectangle {
    width: 20px;
    margin: 20px;
    background-color: #555;
}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>BubbleSort</title>

    <link rel="stylesheet" href="../style.css">
</head>

<body>

    <canvas id="myCanvas" width="800" height="500"></canvas>

    <script src="sketch.js"></script>

    <button type="button" onclick="init()">Bubble Sort</button>

</body>

</html>

最佳答案

fillStyle命令可以更改矩形的颜色!
例如,在您的drawLines函数中,

function drawnLines(array) {
  let height;
  let position = 5;

  ctx.font = "10px Verdana";

  for (i = 0; i < array.length; i++) {
    height = array[i];
    //Here you can enter in a color!
    ctx.fillStyle = "#eee";

    ctx.fillRect(position, 5, 20, height);
    ctx.strokeText(array[i].toString(), position, array[i] + 20);
    ctx.stroke();
    position += 48;
  }
};


可以是十六进制或颜色名称。
如果您希望矩形不同,则可以使用随机颜色生成器,也可以使用数组来帮助设置颜色值,并在绘制矩形时遍历该数组,如下所示:

var mySetColors = ["Red", "Green", "Blue", "#eee"];
var myLocation = 0;

for()...
ctx.fillStyle = mySetColors[myLocation++];
...


您可以参考此站点以获取更多详细说明:https://www.w3schools.com/tags/canvas_fillstyle.asp

关于javascript - 循环更改Rect html Canvas 的颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59363261/

10-14 13:17
查看更多