有什么我认为似乎是一种奇怪的问题。我有一个用于在 HTML5 中绘制元素的函数。如果我多次写它,它会被绘制那些次,但如果我将它放在一个循环中,它只会绘制第一次。例如,我试图通过 console.log 来监控它,但是一旦我尝试绘制它,循环就会被中断。好像里面有某种类型的“中断”功能。
有人对此有任何想法吗?
<body>
<section id="wrapper">
<h1></h1>
<canvas id="canvas" width="800" height="600" style=" border-color: #000; border-style: solid; border-width: 1px;">
<p>Your browser doesn't support canvas.</p>
</canvas>
<script>
var context;
var canvas;
var WIDTH;
var HEIGHT;
$(document).ready(function() {
main_init();
});
function main_init() {
console.log("init");
WIDTH = $("#canvas").width();
HEIGHT = $("#canvas").height();
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
var width = 10;
var height = 10;
var posX = 30;
var posY = 60;
//NOT WORKING
for(y = 1; y < height; y+=1)
{
for(x = 1; x < width; x+=1)
{
console.log("y:"+ y + " x:" + x);
//console.log(isEven(x));
if(isEven(x))
{
HexagonObj(posX * x, posY * y, 0.95);
}
else
{
HexagonObj(posX * x, (posY + 20) * y, 0.95);
}
}
}
//WORKING
HexagonObj(-30, 60, 0.95);
HexagonObj(10, 80, 0.95);
HexagonObj(50, 60, 0.95);
HexagonObj(-30, 100, 0.95);
}
HexagonObj = function(xCorrd, yCorrd, size){
//console.log("hexagon");
var x0=xCorrd; var y0=yCorrd; //cordinates
var xx=20 * size; var yy=20 * size; //size of the legs of the shape
x=x0; y=y0; context.moveTo(x,y);
x+=xx; y+=0; context.moveTo(x,y);
x+=xx; y+=0; context.lineTo(x,y);
x+=xx; y+=yy; context.lineTo(x,y);
x+=(xx*-1); y+=yy; context.lineTo(x,y);
x+=(xx*-1); y+=0; context.lineTo(x,y);
x+=(xx*-1); y+=(yy*-1); context.lineTo(x,y);
x+=xx; y+=(yy*-1); context.lineTo(x,y);
context.fillStyle = "#FFFF99";
context.fill();
context.strokeStyle = "rgba(0,0,0,1)";
context.stroke();
}
function isEven(n)
{
return parseFloat(n) && (n % 2 == 0);
}
</script>
</section>
</body>
我已经标记了HexagonObj
有效的创作和无效的创作。