-
定义全局得canvas对象
canvas: {
//全局canvas对象,用于测量文字宽度
canvasObj: null,
getCanvas: function () {
if (printNurse.model.canvas.canvasObj == null) {
printNurse.model.canvas.canvasObj = document.createElement(“canvas”);
}
return printNurse.model.canvas.canvasObj;
},
getdefaultOptions: function () {
return {
size: 12,
family: “Microsoft YaHei”
};
}
} -
//计算宽的实现方式(注意在实际计算中特殊字符和空格存在计算误差)
-
getActualWidthOfChars: function (text, options = {}) {
const _options = . e x t e n d ( c a n v a s . g e t d e f a u l t O p t i o n s ( ) , o p t i o n s ) ; c o n s t c a n v a s = c a n v a s . g e t C a n v a s ( ) ; c o n s t c t x = c a n v a s . g e t C o n t e x t ( " 2 d " ) ; c t x . f o n t = ‘ .extend(canvas.getdefaultOptions(), options); const canvas = canvas.getCanvas(); const ctx = canvas.getContext("2d"); ctx.font = ` .extend(canvas.getdefaultOptions(),options);constcanvas=canvas.getCanvas();constctx=canvas.getContext("2d");ctx.font=‘{_options.size}px ${_options.family}`;
const metrics = ctx.measureText(text);
return metrics.width;
}