最近沒事看了會canvas的API,發現canvas在繪圖不少方面都很強。可是在文本API上就顯得不夠深刻。css
好比,文本換行,或文本區域等。花了點時間,寫了個小函數。也不知道能不能用上。記錄下。歡迎指教。html
<!DOCTYPE html>
<html>
<meta charset="utf-8">前端
<body>json
<canvas id="myCanvas" width="555" height="444" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>canvas
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");前端工程師
font(ctx,{
text:'個人名字叫andy,今年30,住在北京,<br>是一個前端工程師。謝謝。',
basic:[100,50,200,200],
css:'font-size:30px;line-height:40px;font-family:Arial;color:#fff;background-color:#ccc',
other:{
blank:false,//是否首行空兩格,可選
enter:false,//回車是否空一行
word:false//英文強制單詞換行
}
});函數
function font(ctx,json){
var left=json.basic[0],
top=json.basic[1],
maxWidth=json.basic[2],
maxHeight=json.basic[3],
css=json.css.split(';'),
jsonCss={},
text=json.text,
other=json.other;
ctx.textBaseline='top';
for(var i=0;i<css.length;i++)
{
var css2=css[i].split(':');
jsonCss[css2[0]]=css2[1];
};
var font=jsonCss['font-size']||'';
var family=jsonCss['font-family']||'';
var color=jsonCss['color']||'';
ctx.font=''+font+' '+family;
ctx.fillStyle=jsonCss['color']||'#000';
if(jsonCss['background-color'])
{
ctx.fillStyle=jsonCss['background-color'];
ctx.fillRect(left,top,maxWidth,maxHeight);
};
var fontSize=parseInt(jsonCss['font-size']),
lineHeight=parseInt(jsonCss['line-height']);
var space=parseInt((lineHeight-fontSize)/2);
var enter=other.enter||false;
text=text.split('<br>')!=-1?text.split('<br>'):[text];
var word=other.word||false;
var w=0;
var h=0;
ctx.fillStyle=color;
for(var j=0;j<text.length;j++)
{
var sText=text[j];
var end=false;
w=other.blank?parseInt(font)*2:0;
for(var i=0;i<sText.length;i++)
{
var re=/[a-zA-Z]+/;
if(word)
{
if(re.test(sText[i])&&!re.test(sText[i-1]))
{
var English=sText.substring(i);
var tw=ctx.measureText(English).width;
if(w+tw>maxWidth)
{
w=0;
h+=lineHeight;
};
};
};
var tw=ctx.measureText(sText[i]).width;
if(w+tw>maxWidth)
{
w=0;
h+=lineHeight;
};
if(h+lineHeight>maxHeight)
{
end=true;
break;
};
ctx.fillText(sText[i],left+w,top+h+space);
w+=tw;
};
if(end)break;
h+=lineHeight;
if(enter)h+=lineHeight;
};
};
</script>spa
</body>
</html>3d