Adam Day
Adam Day

Reputation: 57

Javascript Canvas - Circles are changing color

I am having a problem with drawing circles on a canvas. When I draw a circle on my canvas it works fine, but if I draw a square afterwards, the color of my circle changes to the same color as the square.

This has been troubling me for a while now. Here is a jsbin project to demonstrate what I am talking about:

https://jsbin.com/bajezudayi/edit?html,js,output

On this canvas you can draw circles and squares (note the check box at the top to switch shapes).

I have tried changing the color variable in the drawCircle to a set value instead of being a function argument but the problem persists.

function drawCircle(x,y,rad,col,ctx){
  // This function draws a circle on a canvas
    ctx.save();
    ctx.translate(x,y);
    ctx.beginPath();
    ctx.arc(0,0,rad,0,2*Math.PI,false);
    ctx.fillStyle='red'; // rather than =col
    ctx.fill();
    ctx.restore();
}

If I apply an animation loop to my canvas, even weirder effects start to happen because of this issue.

Any ideas why this is happening? Thank you.

Edit: Here is the full project I am currently working on:

http://adam-day-com.stackstaging.com/orbital/index.html

Try checking the 'show vector field' box and add some planets. The function to draw the vector field (called in an animation loop) draws a series of thin boxes and it messes up the circle colors.

Upvotes: 0

Views: 878

Answers (1)

xadhix
xadhix

Reputation: 174

I added ctx.beginPath() and ctx.closePath() and things seem to working fine. Is this what you wanted? https://jsbin.com/ribiyodoru/edit?html,js,output

Upvotes: 2

Related Questions