Reputation: 5525
I have this code to draw some 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 some characters have this strange shape :
Why A
, M,
V
, W
have ugly stroke lines?
Upvotes: 4
Views: 292
Reputation: 9813
It's because the linejoin
property in canvas
is default to miter
, and when the line join angle is smaller, it'll create a sharper join at the point, which will extend longer.
Solution:
ctx.miterLimit
, like ctx.miterLimit=1
.lineJoin
value, like 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>
Upvotes: 4
Reputation: 31839
Use shadow*
, instead of stroke*
:
ctx.textBaseline = “top”
ctx.shadowColor = “#000”
ctx.shadowOffsetX = width;
ctx.shadowOffsetY = 0;
ctx.shadowBlur = blur;
ctx.fillText(text, -width, 0);
Upvotes: 1