javascript - Create multiple times works, but not in for-loop -
have think seems kind of unusual problem. have function made draw element in html5. if write multiple times drawn times, if place in loop draws first time. iv tried monitor console.log illustration seek draw loop interrupted. there type of "break" function in it.
anyone has thought this?
<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 back upwards 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 legs of 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) { homecoming parsefloat(n) && (n % 2 == 0); } </script> </section> </body>
i have marked hexagonobj
creation works , dose not work.
you need declare x
, y
variables in each function used. because missing var
declaration, functions accessing global x
, y
variables. consequence, first phone call hexagonobj
clobbers loop variables in main_init()
.
(technically, need declare var x, y
in 1 of functions solve immediate problem. however, it's bad form using global variables that.)
javascript html5 for-loop break
No comments:
Post a Comment