gpt4 book ai didi

javascript - 循环更改 Rect html Canvas 的颜色

转载 作者:行者123 更新时间:2023-11-28 03:19:01 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com