24个迭代javascript循环仅显示10个画布

时间:2019-01-30 20:00:15

标签: javascript html5-canvas

我想生成24个画布,但是页面上仅显示10个。 我无法使用整个宽度,也无法真正找出原因。 这是一段代码来说明我的示例:https://jsfiddle.net/bLr83jyn/2/

var colors = ['blue', 'green', 'yellow', 'orange', 'red', 'purple'];

function MakeCanvas(x, y, w, h, color) {
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  ctx.fillStyle = color;
  ctx.fillRect(x, y, w, h);
}

var x = 0;
var y = 0;
var w = 30;
var h = w * 1.5;
var offset = w;

for (var i = 0; i < 24; i++) {
  MakeCanvas(x, y, w, h, colors[i % colors.length]);
  x = x + offset;
}
<canvas id="canvas"></canvas>

你知道怎么了吗?

1 个答案:

答案 0 :(得分:1)

您没有为画布指定尺寸,因此使用默认尺寸300 x150。因此,当您渲染10个矩形时,您已经用完了300 px的宽度,所有其余的都绘制在画布的边界之外

如果需要更大的画布,可以将属性添加到canvas元素。例如:

Sub Button3_Click()

Dim lRow As Long
Dim i As Long
Dim toDate As Date
Dim Sheets As Worksheet
Dim r1 As Range

lRow = Cells(Rows.Count, 2).End(xlUp).Row

For i = 2 To lRow
    If Cells(i, 1).Value = "x" Then
        Set r1 = Union(IIf(r1 Is Nothing, Cells(i, 2).Resize(, 3), r1), Cells(i, 2).Resize(, 3))
        Cells(i, 10).Value = "Selected " & Date + Time
    End If
Next i

If Not r1 Is Nothing Then r1.Select

ActiveWorkbook.Save

End Sub
var colors = ['blue', 'green', 'yellow', 'orange', 'red', 'purple'];

function MakeCanvas(x, y, w, h, color) {
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  ctx.fillStyle = color;
  ctx.fillRect(x, y, w, h);
}

var x = 0;
var y = 0;
var w = 30;
var h = w * 1.5;
var offset = w;

for (var i = 0; i < 24; i++) {
  MakeCanvas(x, y, w, h, colors[i % colors.length]);
  x = x + offset;
}

在空间不足之前,可以容纳30个30像素宽的矩形中的20个。或者,您可以渲染较小的矩形。只是取决于您要做什么。