【问题标题】:Strange Font Behaviour On HTML CanvasHTML Canvas 上的奇怪字体行为
【发布时间】:2015-07-03 07:02:02
【问题描述】:

我有这段代码可以在我的 HTML 画布上绘制一些文本:

$("#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);
});

但是为什么有些字符有这种奇怪的形状:

为什么AM,VW的笔划线很丑?

【问题讨论】:

  • fiddle 会很有帮助!

标签: javascript jquery html canvas


【解决方案1】:

这是因为canvas中的linejoin属性默认为miter,当线连接角度较小时,会在该点创建更锐利的连接,从而延长更长的时间。 解决方案:

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

【讨论】:

    【解决方案2】:

    使用shadow*,而不是stroke*

    ctx.textBaseline = “top”
    ctx.shadowColor = “#000”
    ctx.shadowOffsetX = width;
    ctx.shadowOffsetY = 0;
    ctx.shadowBlur = blur;
    ctx.fillText(text, -width, 0);
    

    【讨论】:

      猜你喜欢
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 2021-07-02
      相关资源
      最近更新 更多