skip to Main Content

I’m currently using HTML5’s canvas to render a string using the Impact font. This works fine, but the stroke appears to be bleeding out of the whole text area. Is there any way to fix this?

Code and render can be seen here: http://jsfiddle.net/5uczpa1k/

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.font = "80px Impact";
ctx.strokeStyle = 'black';
ctx.lineWidth = 20;
ctx.fillStyle = 'white';
ctx.strokeText("A TEXT DEMO", 50, 150);
ctx.fillText("A TEXT DEMO", 50, 150);
<canvas id="myCanvas" width="500" height="500"></canvas>

2

Answers


  1. Try adding a miterLimit – this defines a limit on the ratio of the miter (corner) length to the stroke-width used to draw a miter join. When the limit is exceeded, the join is converted from a miter to a bevel:

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    
    ctx.font = "80px Impact";
    ctx.strokeStyle = 'black';
    ctx.lineWidth = 20;
    ctx.fillStyle = 'white';
    ctx.miterLimit = 2;
    ctx.strokeText("A TEXT DEMO", 50, 150);
    ctx.fillText("A TEXT DEMO", 50, 150);
    <canvas id="myCanvas" width="500" height="500"></canvas>
    Login or Signup to reply.
  2. ctx.lineJoin = 'bevel';
    

    The stroke is always drawn half inside and half outside, unless you make the necessary calculations to do something different yourself and draw two separate shapes, one for the fill and one for the outline. The default half-and-half approach is applied even when the lineWidth is an odd number, in which case the browser will attempt to draw halfway between two actual pixels, resulting in blurring and loss of colour intensity (unless you shift the canvas by 0.5px in both dimensions by applying a translation transform). This is more of a problem when translucency is involved. You have an opaque fill being performed after the stroke. So the net effect is that your outline effectively becomes "outside" but its apparent width is half of the width stated in the code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search