I recently read the canvas API and found that canvas is very strong in many aspects of drawing. However, the text API is not in-depth enough.
For example, Text wrap or text area. It took some time to write a small function. I don't know if it can be used. Record. Thank you for your advice.
<! Doctype HTML>
<HTML>
<Meta charset = "UTF-8">
<Body>
<Canvas id = "mycanvas" width = "555" Height = "444" style = "border: 1px solid # d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</Canvas>
<SCRIPT>
VaR c = Document. getelementbyid ("mycanvas ");
VaR CTX = C. getcontext ("2D ");
Font (CTX ,{
Text: 'My name is Andy. I live in Beijing 30 this year. <br> I am a front-end engineer. Thank you. ',
Basic: [200,200, 50,],
CSS: 'font-size: 30px; line-Height: 40px; font-family: Arial; color: # FFF; Background-color: # CCC ',
Other :{
Blank: false, // whether the first line has two blank cells. Optional.
Enter: false, // enter whether a row is empty
Word: false // force line feed in English
}
});
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>
</Body>
</Html>
Encapsulate canvas Text Functions