hzqij1978
hzqij1978

Reputation: 283

HTML5 Canvas Line Width Bug?

I have code like:

context.strokeStyle = "navy";
context.lineWidth = 4;

context.beginPath();

var points = [
    {x:605, y:149},
    {x:613, y:131 },
    {x:875, y:244},
    {x:779, y:224}
];

for (var i = 0; i < points.length; i++) {
    if (i === 0) {
        context.moveTo( points[i].x, points[i].y );
    }
    else {
        context.lineTo( points[i].x, points[i].y );
    }
}

context.closePath();
context.stroke();

context.strokeStyle = "red";
context.beginPath();

points = [
    {x:565, y:224},
    {x:565, y:244},
    {x:875, y:244},
    {x:779, y:224}
];

for (i = 0; i < points.length; i++) {
    if (i === 0) {
        context.moveTo( points[i].x, points[i].y );
    }
    else {
        context.lineTo( points[i].x, points[i].y );
    }
}

context.closePath();

context.stroke();

but the result is very strange on intersection points {x:875, y:244},two line Extended.

when I set linewidth=1, the result is good

what's the problem? how can I fix the code to look well when linewidth large than 1.

Upvotes: 1

Views: 409

Answers (1)

user1693593
user1693593

Reputation:

It's due to default line-join mode being miter and miter limit is set to 10. This will attempt to create a sharp join which sometimes mean the joined peak will move some ahead where angles get steep.

Lower miterLimit (before stroking), and it should work:

context.miterLimit = 1;

Optionally, try different join types like:

context.lineJoin = "round";
context.lineJoin = "bevel";

Upvotes: 1

Related Questions