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

谁说我不能喝 提交于 2020-01-09 11:46:08

问题


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 I apologise for, been moving things between the two functions - Not sure how to refer to the context non-explicitly):

function drawCircle(ctx,x,y,radius, color){
  var startAngle = 0;
  var endAngle = (Math.PI*2);
  var clockwise = true;
  ctx.fillStyle = color;
  ctx.arc(x,y,radius,startAngle,endAngle, clockwise);
  ctx.fill();
  ctx.closePath;
}
function drawCircles(){
    var canvas = document.getElementById('myCanvasArea');  
    var ctx = canvas.getContext('2d'); 
     if (canvas.getContext){    
        drawCircle(ctx,50,25,25, 'blue');
        drawCircle(ctx,100,25,25, 'black');
    }
}

I get two black circles. I presume I'm not differentiating between the two shapes, therefore the properties of the 2nd are applied to the 1st.

How do I make that distinction? I was thinking of making clicking each one raise an action. Am I going about this incorrectly from the start?


回答1:


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/



来源:https://stackoverflow.com/questions/8457056/all-html-canvas-shapes-are-given-the-color-of-the-last-object-added

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!