Question

I have a function here that's supposed to draw a square and a plus sign in the middle, then reverse colors if the mouse is over it. It works fine if the mouse is not on top, but once it is filled, the plus sign disappears. I assume it's being covered up.

function drawAdd(cx, cy, btnW, btnH, mouse)
{
    var getID = document.getElementById("canvas_1");
    var color = "black";
    var px = cx + btnW/2;
    var py = cy + btnH/2;

    if (getID.getContext)
    {
        var ctx = getID.getContext("2d");

        ctx.clearRect(cx, cy, btnW, btnH);
        ctx.lineWidth = "10";
        ctx.fillStyle = "black";

        if(mouse)
        {
            ctx.fillRect(cx, cy, btnW, btnH);
            color = "white";
        }
        else
        {
            ctx.strokeRect(cx, cy, btnW, btnH);
        }

        ctx.beginPath();
        ctx.lineWidth = "20";
        ctx.fillStyle = color;
        ctx.moveTo(px - 40, py);
        ctx.lineTo(px + 40, py);
        ctx.moveTo(px, py - 40);
        ctx.lineTo(px, py + 40);
        ctx.stroke();
        ctx.closePath();
    }
}

What am I doing wrong here?

Was it helpful?

Solution

You need to replace ctx.fillStyle = color with ctx.strokeStyle = color as line color is set by strokeStyle, not fillStyle.

Here's a working JSFiddle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top