[英]javascript canvas - generating a dynamic grid of squares on a canvas
I am working on a simple program in JS that creates a grid of squares on a canvas of any size. 我正在用JS开发一个简单的程序,该程序可以在任何大小的画布上创建正方形网格。 I am able to generate half the grid but for some reason my other half does not appear on the screen.
我能够生成一半的网格,但是由于某种原因,我的另一半没有出现在屏幕上。
could anyone see a potentially flaw in my logic? 谁能看到我的逻辑上的潜在缺陷?
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="500px" height="500px" style="border:1px solid #d3d3d3;">
</canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var x = 0;
ctx.fillStyle = "black";
ctx.fillRect(x, 0, canvas.width / 2, canvas.height);
while (x < canvas.width / 2) {
var y = 0;
while (y < canvas.height) {
ctx.beginPath();
ctx.fillStyle = "#77f442";
ctx.fillRect(x + 30, y + 10, 20, 20);
ctx.stroke();
y = y + 50;
}
x = x + 50;
}
//var x = canvas.width / 2;
while ((x >= (canvas.width / 2)) && (x < canvas.width)) {
var y = 0;
while ((y >= (canvas.height)) && (y < canvas.height)) {
ctx.beginPath();
ctx.fillStyle = "#77f442";
ctx.fillRect(x + 10, y + 10, 20, 20);
ctx.stroke();
y = y + 50;
}
x = x + 50;
}
</script>
</body>
</html>
I had a logic error where I was checking for (y >= (canvas.height)
我在检查
(y >= (canvas.height)
遇到逻辑错误
the fix was to use <
instead of >=
解决方法是使用
<
而不是>=
correct code: 正确的代码:
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var x = 0;
ctx.fillStyle = "black";
ctx.fillRect(x, 0, canvas.width / 2, canvas.height);
while (x < canvas.width) {
if (x < canvas.width / 2) {
var y = 0;
while (y < canvas.height) {
ctx.beginPath();
ctx.fillStyle = "#77f442";
ctx.fillRect(x + 30, y + 10, 20, 20);
ctx.stroke();
y = y + 50;
}
x = x + 50;
}
else if (x == canvas.width / 2)
{
while ((x >= (canvas.width / 2)) && (x < canvas.width)) {
var y = 0;
while ((y <= (canvas.height))) {
ctx.beginPath();
ctx.fillStyle = "#77f442";
ctx.fillRect(x , y + 10, 20, 20);
ctx.stroke();
y = y + 50;
}
x = x + 50;
}
}
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.