[英]Creating lots of rects with html5 canvas
I am creating a program in javascript that takes a number, converts it to binary, then fills in a series of cells based on whether they correspond to a one or zero in the binary number. 我正在用JavaScript创建一个程序,该程序需要一个数字,将其转换为二进制,然后根据它们对应于二进制数中的一个还是零填充一系列单元格。 I am starting to create the mechanics.
我开始创建机制。
To fill in many cells at once I am using this code: 要一次填充许多单元格,请使用以下代码:
function init() {
canvas = document.getElementById("display");
ctx = canvas.getContext('2d');
draw();
}
function draw() {
for (var x = 0; x += 25; x < 250) {
for (var y = 0; y += 25; y < 250) {
if (y % 2 == 0) {
ctx.fillStyle = "rgb(0, 0, 0)";
} else {
ctx.fillStyle = "rgb(255, 255, 255)";
}
ctx.fillRect(x, y, 25, 25);
}
}
}
window.onload = init;
This seems to be a very bad way of doing it. 这似乎是一个非常糟糕的方法。 It causes some cells not to be filled in, makes the program very slow, and stops it entirely.
这会导致某些单元格无法填充,使程序非常缓慢,并完全停止运行。 The only alternative I can think of is hundreds of lines of
ctx.fillRect()
. 我能想到的唯一替代方法是
ctx.fillRect()
数百行。 Is there a better way of filling in many rectangles? 有没有更好的方法来填充许多矩形?
This is because you have an infinite loop in your code. 这是因为您的代码中存在无限循环。
Remember, the syntax for for
loops is: 记住,
for
循环的语法是:
for(variable;condition;variable-change) {
//block of code
}
You switched the condition
and variable-change
segments, making it be infinite because x += 25
is not a conditional that can be evaluated to true
or false
. 您切换了
condition
段和variable-change
段,使其成为无穷大,因为x += 25
不是可以评估为true
或false
。 Instead, it will always be true
because you are merely assigning a variable a new value. 相反,它总是
true
因为您只是在为变量分配新值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.