canvas 文本样式处理
文本居中和自动换行
var _self = this
var _canvas = document.createElement('canvas');
var _context = _canvas.getContext("2d")
_canvas.width = 500
_canvas.height = 600
//调用示例
var _obj = {
ontList: '测试文案',
isCenter: false,
top: 120,
leftAndright: 10,
lineH: 13,
lineW: 0,
font: '30px Courier New',
fillStyle: 'black'
}
determineNumberRows(_obj)
//fontList:文本内容 ,
//isCenter: 不满一行是否要文本居中,
//top: 距顶部高度,
//leftAndright:左右边距,
//lineH: 行高,
//lineW,文字的间距
function determineNumberRows(_obj,_w = _obj.leftAndright + _obj.lineW / 2) {
_context.font = _obj.font
var _font_w = _context.measureText('例').width + _obj.lineW / 2
var _h = _obj.top + _font_w
var _k = false
_context.fillStyle = _obj.fillStyle
if(_obj.isCenter) _w = (_canvas.width - _obj.fontList.split('').length * (_font_w + _obj.lineW / 2) + _obj.leftAndright * 2) / 2
_obj.fontList.split('').forEach((T,I)=> {
if(_obj.isCenter && _canvas.width > (_obj.fontList.split('').length * (_font_w + _obj.lineW / 2) + _obj.leftAndright)) {
if(_k) _w += _font_w + _obj.lineW / 2
_k = true
} else {
if(_canvas.width <= _w + _font_w + _obj.leftAndright + _obj.lineW / 2) {
_h += _font_w + _obj.lineH
_w = _obj.leftAndright + _obj.lineW / 2
} else {
if(_k) _w += _font_w + _obj.lineW / 2
_k = true
}
}
_context.fillText(T,_w,_h);
})
_self.base64 = _canvas.toDataURL("image/png")
}