我认为这似乎是一种奇怪的问题。我有一个用来在HTML5中绘制元素的函数。如果我多次写它,它就会被绘制多次,但如果我把它放在一个循环中,它只会在第一次绘制。例如,Iv试图通过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创建。
发布于 2013-02-15 15:15:37
您需要在使用x和y的每个函数中将它们声明为变量。因为您缺少var声明,所以函数都访问全局x和y变量。因此,第一次调用HexagonObj会阻塞main_init()中的循环变量。
(从技术上讲,您只需在其中一个函数中声明var x, y即可解决当前问题。然而,使用这样的全局变量是不好的形式。)
https://stackoverflow.com/questions/14889793
复制相似问题