2012-11-29 28 views
10

我正在使用HTML5的畫布使用fillText方法呈現多個字符串。這工作正常,但我也想給每個字符串1px黑色外部描邊。不幸的是,strokeText函數似乎應用了一個內部中風。爲了解決這個問題,我寫了一個drawStrokedText函數來實現我之後的效果。不幸的是它很慢(顯而易見的原因)。使用HTML5的畫布繪製具有外部筆畫的文本

是否有一種使用本地畫布功能實現1px外部筆劃的快速,跨瀏覽器方式?

drawStrokedText = function(context, text, x, y) 
{ 
    context.fillStyle = "rgb(0,0,0)"; 
    context.fillText(text, x-1, y-1); 
    context.fillText(text, x+1, y-1); 
    context.fillText(text, x-1, y); 
    context.fillText(text, x+1, y); 
    context.fillText(text, x-1, y+1); 
    context.fillText(text, x+1, y+1); 

    context.fillStyle = "rgb(255,255,255)"; 
    context.fillText(text, x, y); 
}; 

這裏工作時的效果的例子:

enter image description here

+0

如何渲染與'strokeText'文本,但有一個稍大的字體,以佔內中風? 另外,在'drawStrokedText'方法上,你可以跳過水平/垂直移位。 (你似乎已經失去了垂直,任何方式) – Cerbrus

回答

32

這有什麼錯中風?由於筆劃的一半將在形狀之外,所以您總是可以首先用您想要的雙倍線寬來繪製筆畫。所以,如果你想要一個4PX外行程,你可以這樣做:

function drawStroked(text, x, y) { 
    ctx.font = "80px Sans-serif" 
    ctx.strokeStyle = 'black'; 
    ctx.lineWidth = 8; 
    ctx.strokeText(text, x, y); 
    ctx.fillStyle = 'white'; 
    ctx.fillText(text, x, y); 
} 


drawStroked("37°", 50, 150); 

這使得:

enter image description here

現場小提琴這裏:http://jsfiddle.net/vNWn6/


如果出現這種情況不爲看在較小的文本渲染尺度下精確,您可以隨時將其繪製得較大但將其縮小(在上面的例子中,您可以使用ctx.scale(0.25, 0.25)

+1

我添加了一些額外的代碼以及下面的鏈接來擦亮這一點。儘管如此,西蒙爲這個聰明的解決方案+1! – Jackalope

+0

謝謝你的回答! – Aircraft5

1

對於光影你可以試試這個

ctx.beginPath(); 
ctx.fillStyle = 'white'; 
ctx.font = "bold 9pt Tahoma"; 
ctx.shadowBlur = 3; 
ctx.textAlign = "center"; 
ctx.shadowColor = "#000000"; 
ctx.shadowOffs = 0;     
ctx.fillText('www.ifnotpics.com', 100, 50);   
ctx.closePath();