Jquery画布绘制不一致的形状

Jquery Canvas drawing inconsistent shapes

本文关键字:不一致 绘制 布绘制 Jquery      更新时间:2023-09-26

我一直在网上搜索,盯着这段代码看了一段时间,我就是弄不明白。如有任何帮助,我将不胜感激。

我正在尝试制作一个图表,其中用户输入尺寸,并且画布持有一个图表,其中用户可以单击每个框,并更改该框的阴影。然而,由于某些原因,这些方框只填充了图表的一部分。

my HTML file:

<body>
        <canvas id="box"></canvas>  
        <script>
            var canvas = document.getElementById('box');
            var ctx = canvas.getContext('2d');
        </script>
        ...
        <button type="button" id="buildDiagram">Go!</button>
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/diagramFuncts.js"></script>  
</body>

diagramFuncts.js:

  $('#buildUry').click(function() {
    ....
            ctx.fillStyle = "rgb(252,252,252)";
            ctx.fillRect(0, 0, width, height);
            //each box is 50 by 50 and the boxes populate the canvas from the upper left corner
            for (i = 0; i < rows; ++i) {
                for (j = 0; j < cols; ++j) {
                    ctx.fillRect(50*j, 50*i, 50, 50);       
                    ctx.strokeRect(50*j, 50*i, 50, 50);
                }
            }
  });

这段代码生成了一个正确大小的画布,但是没有正确填充。例如,一个2 × 3的图表是100x150像素,但是里面的盒子太小了。

如果有人发现我代码中的任何错误,我将非常感激。

现场演示

这两行只需要交换i和j。

ctx.fillRect(50 * i, 50 * j, 50, 50);
ctx.strokeRect(50 * i, 50 * j, 50, 50);

列(J)将是Y的第二个参数,行(I)将是x的第一个参数。

var canvas = document.getElementById('box');
var ctx = canvas.getContext('2d');
var rows = 2,
    cols = 3,
    width = rows*50,
    height = cols*50;
canvas.width = width;
canvas.height = height;

ctx.fillStyle = "rgb(252,252,252)";
ctx.fillRect(0, 0, width, height);
//each box is 50 by 50 and the boxes populate the canvas from the upper left corner
for (i = 0; i < rows; ++i) {
    for (j = 0; j < cols; ++j) {
        ctx.fillRect(50 * i, 50 * j, 50, 50);
        ctx.strokeRect(50 * i, 50 * j, 50, 50);
    }
}