javascript - Jquery Canvas 绘制不一致的形状

标签 javascript jquery canvas

我一直在互联网上搜索并盯着这段代码一段时间,但我就是无法弄清楚。任何帮助将不胜感激。

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

我的html文件:

<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);
                }
            }
  });

此代码生成正确尺寸的 Canvas ,但未正确填充。例如,2 x 3 的图表是 100x150 像素,但内框的尺寸太小。

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

最佳答案

Live Demo

这两行只需交换 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);
    }
}

关于javascript - Jquery Canvas 绘制不一致的形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24368773/

相关文章:

JQuery Mobile Form data-ajax ="false"使用计时器自动提交

javascript - Canvas HTML5 和 jquery,删除内容

javascript - 使用 JQUERY 选择带有 .on ('change' ) 事件的动态插入的 Div 元素

javascript - 如何将 "background-color"转换为 rgb() 格式?

javascript - for of 在JS中是如何实现的

javascript - HTML Canvas 在 Canvas 下方而不是 Canvas 内部显示图像

javascript - Canvas for() 循环、lineTo() 和 closePath()

javascript - JWT:在到期后一分钟或更短时间内将新 token 传递给客户端。坏主意还是好主意?

javascript - 在浏览器中,在窗口滚动时中断

javascript - ajax添加后检查div是否有特定文本