2015-07-03 32 views
4

我有這樣的代碼動用我的HTML畫布一些文字:奇怪的字體行爲對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); 
}); 

但是,爲什麼有些字符有這個奇怪的形狀:

html canvas font issue

爲什麼AM,V,W有難看的中風線?

+1

一個'fiddle'將是非常有益的! –

回答

4

這是因爲在canvaslinejoin屬性默認爲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>

1

使用shadow*,而不是stroke*

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