Skip to content

Instantly share code, notes, and snippets.

@xiaojue
Created March 15, 2014 09:43
Show Gist options
  • Save xiaojue/9564142 to your computer and use it in GitHub Desktop.
Save xiaojue/9564142 to your computer and use it in GitHub Desktop.
canvas text 自动换行 文本转长微博
<html>
<head>
<title>canvas demo</title>
</head>
<body>
<textarea id="text" style="width:300px;height:100px;"></textarea>
<br>
<button id="toImg">转化</button>
<br>
<canvas style="border:#ccc solid 1px;" id="weiboText"></canvas>
<script>
function $(id){
return document.getElementById(id);
}
var text = $('text'),
toimgbtn = $('toImg'),
target = $('weiboText');
var maxWidth = 500;//最宽500像素,否则换行
var linemargin = 5;
var lineheight = 20;
target.width = maxWidth;
toimgbtn.addEventListener('click',function(){
var txt = text.value;
var context = target.getContext('2d');
//自动换行逻辑
var insertTextData = [];
var i,x = 0 ,y = 0,linesize = 1;//初始位置
for(i = 0 ; i<txt.length;i++){
var currentWord = txt.charAt(i);
var nextWord = txt.charAt(i + 1) || '';
if (currentWord == ' ') continue;
var currentWidth = context.measureText(currentWord).width;
var nextWidth = context.measureText(nextWord).width;
if(x + nextWidth >= maxWidth || currentWord == '\n'){
x = 0;
linesize ++;
}
y = (lineheight + linemargin) * linesize;
insertTextData.push({
text:currentWord,
x:x,
y:y
});
x = x + currentWidth;
}
target.height = y;
context.clearRect(0,0,maxWidth,y);
for(i = 0;i<insertTextData.length;i++){
var item = insertTextData[i];
context.fillText(item.text,item.x,item.y);
}
context.save();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment