我正在努力在棋盘上创建多个棋盘 到目前为止,我有此JS代码:
<script>
$(document).ready(function() {
var gColor = "black";
var c = $("#myCanvas")[0];
var ctx = c.getContext("2d");
ctx.lineWidth = 2;
ctx.strokeStyle = "black"; //set the color, gradient, or pattern for stroke
drawBoard();
$("#color").click(function () {
gColor = $("#color").val();
if (gColor > "")
drawBoard();
});
function drawBoard() {
var x, y, step = 60, step2 = 120;
ctx.rect(0,0,480,480);
ctx.stroke();
ctx.save();
for (var k=0; k<2; k++) {
step2 -= step;
ctx.translate(0, step*k);
console.log("translate:("+0+","+step*k+")");
for (var y=0; y<4; y++) {
for (var i=0; i<4; i++) {
x = i * 2 * step + step2;
ctx.fillStyle = gColor;
ctx.fillRect(x,y*step*2,step,step);
console.log("fillRect: "+x+","+y*step*2+","+step+","+step+","+gColor);
}
}
}
ctx.restore();
}
var c = $("#myCanvas")[0];
var ctx = c.getContext("2d");
var rad = 90;
for (var i=0; i<1; i++) {
switch (i) {
case 0: ctx.fillStyle = "red";
break;
}
ctx.beginPath();
// Draw circle (x, y, radius, starting angle, ending angle in radian)
ctx.arc(30, 30, 30, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
}
});
</script>
我知道我需要进行某种循环,但是因为我只是在学习画布,所以不知道从哪里开始。任何帮助或建议,谢谢
答案 0 :(得分:0)
for (var i=0; i<1; i++) {
switch (i) {
case 0: ctx.fillStyle = "red";
break;
}
ctx.beginPath();
// Draw circle (x, y, radius, starting angle, ending angle in radian)
ctx.arc(30, 30, 30, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
您正在绘制的圆在for循环之外,并且具有30的硬编码值x和30的Y硬编码
您需要使用与创建黑色正方形相同的逻辑来创建圆形
您的平方数是60、60,
var size = 60;
var rows = 8;
var cols = 8;
for (let i=0; i < rows; i++) {
for (let j=0; j < cols; j++) {
// J is the column Identifier
// I is the row identifier
var x = j*size + (size/2); // j*size takes the center of cicle at the begining of current square + size/2 makes it at the exact center of square
var y = i*size + (size/2); // i*size takes the center of circle at the top of current square, same to bring vertical center size/2 is added
ctx.beginPath();
// Draw circle at (x, y, radius, starting angle, ending angle in radian)
ctx.arc(x, y, (size/2), 0, 2 * Math.PI); // radius is half of square width
ctx.fill();
ctx.stroke();
}
}
这将在每个正方形处绘制圆。
问题不在于画布,而是迭代和计算圆的x和y位置的简单逻辑。我认为您应该多读一些有关循环的内容,这将对您有进一步的帮助。