HTML画布上的奇怪字体行为

时间:2015-07-03 07:02:03

标签: javascript jquery html5 canvas

我有这段代码在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);
});

但是为什么有些角色有这种奇怪的形状:

html canvas font issue

为什么AM, VW有难看的笔画线?

2 个答案:

答案 0 :(得分:4)

这是因为linejoin中的canvas属性默认为miter,当线条连接角度较小时,它会在该点创建更清晰的连接,这将扩展更长的时间。 解决方案:

  1. 设置ctx.miterLimit,例如ctx.miterLimit=1
  2. 使用其他lineJoin值,例如round,`
  3. 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>

答案 1 :(得分:1)

使用 <style name="FullScreenTheme" parent="@style/Theme.AppCompat.Light.NoActionBar"> <item name="android:windowNoTitle">true</item> <item name="windowActionBar">false</item> <item name="colorAccent">@color/orange_color</item> <!--Default Text Color --> <item name="android:textColor">@android:color/black</item> <item name="android:textColorHint">@android:color/darker_gray</item> <item name="android:textColorPrimary">@android:color/black</item> </style> 代替shadow*

stroke*