All html canvas shapes are given the color of the last object added

后端 未结 1 1237
挽巷
挽巷 2020-12-02 02:05

I was trying to do an Olympic type flag, purely as a way of learning how to draw in JavaScript. This should draw two circles - one blue, one black... Here is the code (which

相关标签:
1条回答
  • 2020-12-02 02:45

    It's because you are never calling beginPath()!

    function drawCircle(ctx,x,y,radius, color){
      var startAngle = 0;
      var endAngle = (Math.PI*2);
      var clockwise = true;
      ctx.fillStyle = color;
      ctx.beginPath(); // <-- Need me!!
      ctx.arc(x,y,radius,startAngle,endAngle, clockwise);
      ctx.fill();
      ctx.closePath;
    }
    

    Since you don't call beginPath, you are drawing one blue circle, then you are continuing a path that now has two circles (the old one and the new one), and drawing that path (and thus both circles) black!

    Instead you want to draw one blue circle, fill it blue, begin a new path, and draw that one black.

    Live code:

    http://jsfiddle.net/5PDUb/1/

    0 讨论(0)
提交回复
热议问题