I Am Working On An Html 5 Canvas And Trying To Draw Circles On It, But As I Trying To Use A Loop All Disappears
All good until I trying to put the for loop in(no matter what I am meant to use the loop for).
Solution 2:
Here is your code refactored:
Save each circle definition in a javascript object:
var circle1={x:200,y:200,radius:200}; var circle2={x:200,y:0,radius:10};
Save all the circle-objects in an array:
var circles=[]; circles.push(circle1); circles.push(circle2);
Create a function that draws 1 circle from a specified circle-object:
function drawCircle(circle){ ctx.beginPath(); ctx.arc(circle.x,circle.y,circle.radius,0,2*Math.PI); ctx.closePath(); ctx.stroke(); }
Create a function that iterates through the array and draws all the circles:
function drawAll(){ for(var i=0;i<circles.length;i++){ drawCircle(circles[i]); } }
Putting it all together...Here's a demo:
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var circles=[];
circles.push({x:200,y:200,radius:200});
circles.push({x:200,y:0,radius:10});
drawAll();
function drawAll(){
for(var i=0;i<circles.length;i++){
drawCircle(circles[i]);
}
}
function drawCircle(circle){
ctx.beginPath();
ctx.arc(circle.x,circle.y,circle.radius,0,2*Math.PI);
ctx.closePath();
ctx.stroke();
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<canvas id="canvas" width=400 height=400></canvas>
Solution 3:
In html
<canvas id="MyCanvas" width="400" height="400"
style="border:1px solid #000000;">
</canvas>
In script
</script>
for(var i=0; i<2; i++){
var c = document.getElementById("MyCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(200,200,50,0,2*Math.PI);
ctx.stroke();
ctx.beginPath();
ctx.arc(200,10,10,0,2*Math.PI);
ctx.stroke();
}
</script>
see jsfiddle Demo
Post a Comment for "I Am Working On An Html 5 Canvas And Trying To Draw Circles On It, But As I Trying To Use A Loop All Disappears"