L4undry L4undry - 6 months ago 11
HTML Question

Canvas elements changing colors when not supposed to?

I am trying to make an HTML5 canvas checkers game.

I made a JSFiddle of my project: https://jsfiddle.net/0q6thfq8/

Here is the function that I think might be causing the issue: (line 77)

this.drawCheckers = function() {
this.drawSquares();
for(var checker of this.checkers) {
checker.draw();
}
if(this.selection != null) {
ctx.strokeStyle = "green";
ctx.lineWidth = "5";
ctx.rect(this.selection.x,this.selection.y,64,64);
ctx.stroke();
}
}


For some reason, when selecting a checker, the last black checker gets a green outline.

Due to the uniqueness of the problem I am having, I am having a hard time finding other forum posts and websites that talk about this problem.

Could someone shed some light on this problem? Thanks.

K3N K3N
Answer

Add in a beginPath():

if(this.selection != null) {
    ctx.beginPath();
    ctx.strokeStyle = "green";
    ctx.lineWidth = "5";
    ctx.rect(this.selection.x,this.selection.y,64,64);
    ctx.stroke();
}

Fiddle

This will clear the path before drawing a new selection. Otherwise the old path content would be included.

Also remember that ellipse() needs a polyfill in some browsers.