我一直在互联网上搜索并盯着这段代码一段时间,但我就是无法弄清楚。任何帮助将不胜感激。
我正在尝试制作一个图表,其中用户输入尺寸,并且 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/