Strange font behavior on HTML canvas

I have this code to draw text on my HTML canvas:

$("#canvastext").keyup(function(){              
ctx.lineWidth  = 8;
ctx.font = '20pt Arial';
ctx.strokeStyle = 'black';
ctx.fillStyle = 'white';
ctx.textAlign = 'center';

var text = document.getElementById('canvastext').value;

text = text.toUpperCase();
x = canvas.width/2;
y = canvas.height - canvas.height/4.5;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeText(text, x, y);
ctx.fillText(text, x, y);
});

But why do some characters have this strange shape:

html canvas font issue

Why A, M, V, Whave the ugly dotted lines?

+4
source share
2 answers

This is because the property linejoinin canvasis equal by default miter, and when the angle of the line connection is smaller, it will create a sharper connection at the point, which will extend longer. Decision:

  • Set ctx.miterLimitfor example ctx.miterLimit=1.
  • Use a different value linejoin, for example round, `

var canvas =  document.getElementById('cv');
var canvas2 =  document.getElementById('cv2');
var ctx = canvas.getContext('2d');
var ctx2 = canvas2.getContext('2d');
$("#canvastext").keyup(function(){              
     ctx.lineWidth  = 8;
     ctx.font = '20pt Arial';
     ctx.strokeStyle = 'black';
     ctx.fillStyle = 'white';
     ctx.textAlign = 'center';
     ctx.miterLimit = 2;
    
     ctx2.lineWidth  = 8;
     ctx2.font = '20pt Arial';
     ctx2.strokeStyle = 'black';
     ctx2.fillStyle = 'white';
     ctx2.textAlign = 'center';
     ctx2.lineJoin = 'round';
     
     var text = document.getElementById('canvastext').value;
     text = text.toUpperCase();
     x = canvas.width/2;
     y = canvas.height - canvas.height/4.5;
     ctx.clearRect(0, 0, canvas.width, canvas.height);
     ctx.strokeText(text, x, y);
     ctx.fillText(text, x, y);
    
     x = canvas2.width/2;
     y = canvas2.height - canvas.height/4.5;
     ctx2.clearRect(0, 0, canvas.width, canvas.height);
     ctx2.strokeText(text, x, y);
     ctx2.fillText(text, x, y);
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="canvastext"/><br/>
<canvas id="cv" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<canvas id="cv2" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
Run codeHide result
+4
source

Use shadow*instead stroke*:

ctx.textBaseline = "top"
ctx.shadowColor = "#000"
ctx.shadowOffsetX = width;
ctx.shadowOffsetY = 0;
ctx.shadowBlur = blur;
ctx.fillText(text, -width, 0);
+1
source

All Articles