简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM