我有新项目: 15绘制一个包含5行的框,这样一旦将代码写入fillRect()函数。 每行对应当前行的数字为正方形(例如,在三个正方形的第三行)。为什么不起作用:(
const fn = () => x;
const x = 42;
const _fn = `${fn.toString()} || ${x}`;
console.log(_fn, eval(_fn)());
答案 0 :(得分:1)
您错过了内循环代码周围的花括号,当需要在其他行上添加其他框时,您无法移动x,y值。
有关详细信息,请参阅内联评论:
var can = document.getElementById('myCanvas');
can.style.width = "500px";
can.style.height = "500px";
var ctx = can.getContext('2d');
var x = 10;
var y = 10;
var w = 10;
var h = 10;
// Need to keep track of a horizontal indentation amount
// on rows where more than one box should be drawn.
var offsetX = 0;
for(i = 1; i < 6; i++){
// Each new row should have the default indentaion
offsetX = 10;
// This loop needs to execute the amount of times that the
// outer loop has run (i.e. when i is 1, j should be 2
// so that this loop will run once. This loop also needs
// curly braces around its code.
for(j = 1; j < i + 1; j++){
ctx.fillStyle = '#fff947';
ctx.strokeRect(x + offsetX, y, w, h);
ctx.fillRect(x + offsetX, y, w, h);
// On a given row, after making a box, increase the horizontal offset
// by the width of one box.
offsetX += w;
}
// After a row has been made, increase the vertical offset so that the
// next boxes go below the previous ones. Change the y value to be the
// old y value plus the height of a box plus 5 pixels just for a margin
// between rows.
y += (h + 5);
}
&#13;
<canvas id="myCanvas"></canvas>
&#13;