I am working on an html 5 canvas and trying to dra

2019-09-18 08:35发布

问题:

All good until I trying to put the for loop in(no matter what I am meant to use the loop for).

 <canvas id="MyCanvas" width="400" height="400"
style="border:1px solid #000000;">
</canvas>

<script>
  function(){
  var c = document.getElementById("MyCanvas");
  var ctx = c.getContext("2d");
  ctx.beginPath();
  ctx.arc(200,200,200,0,2*Math.PI);
  ctx.stroke();
  ctx.beginPath();
  ctx.arc(200,0,10,0,2*Math.PI);
  ctx.stroke();
  for(int i=0; i<2; i++){

      return i;}
  }

</script>

回答1:

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>



回答2:

There is no int keyword in JavaScript. You should use the var keyword instead. Also note that each function can only have 1 returned value. The for loop in your code doesn't make a lot of sense.



回答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