DougN
DougN

Reputation: 4607

Why isn't rectangle black in HTML 5 canvas?

Below is a simple HTML 5 page with a canvas tag. On the canvas a rectangle is drawn in black, and black text is shown. But for some reason, the rectangle is actually grey. To make it black, I have to draw it 2 or 3 times on top of itself. That seems to indicate there is some sort of alpha issue going on, but I don't know why that would be.

ALSO, the line width looks quite a bit more than 1px wide.... ?

Can anyone show me what I'm doing wrong?

function draw()
{
    var canvas = document.getElementById('tutorial');
    if (canvas.getContext)
    {
        var ctx = canvas.getContext('2d');
        //ctx.globalAlpha = 1;
        //ctx.globalCompositeOperation = "source-over";

        ctx.lineWidth = "1";
        ctx.strokeStyle = "#000000";
        ctx.strokeRect(100, 100, 50, 50); //appears grey

        ctx.font = "22px Arial";
        ctx.fillStyle = "#000000";
        ctx.fillText("test", 120, 120); //appears black as expected
    }
}

Upvotes: 3

Views: 2353

Answers (1)

Tim Ackroyd
Tim Ackroyd

Reputation: 635

Your line looks fat and grey as it is overlapping pixels when it is drawn - i.e. your line straddles two pixels. If you change your code to:

ctx.strokeRect(100.5, 100.5, 50, 50);

You'll see a solid black line.

enter image description here

See this page for more information: http://diveintohtml5.info/canvas.html#paths

Upvotes: 7

Related Questions