一、文字图片不清晰有锯齿
var canvasBox = document.getElementById('mycanvas');
var ctx = canvasBox.getContext('2d');
var getPixelRatio = function (ctx) {
var backingStore = ctx.backingStorePixelRatio ||
ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
};
var scale = getPixelRatio(ctx);
var cwidth = canvasBox.width;
var cheight = canvasBox.height;
canvasBox.style.width = cwidth + 'px';
canvasBox.style.height = cheight + 'px';
canvasBox.width = cwidth*scale;
canvasBox.height = cheight*scale;
ctx.scale(scale,scale);
二、使用html2canvas将画布生成图片不清晰问题
画布生成图片很不清晰,文字有锯齿,用了上述的方法也不行,结果发现是引用的html2canvas.js版本太老了
html2canvas(document.querySelector('#mycanvas'), {
allowTaint: true, //允许污染
useCORS: true, //使用跨域(当allowTaint为true时这段代码没什么用)
background : '#fff',
width: cwidth,
height: cheight
}).then((canvas) => {
var canvasImg = `<img src='${canvas.toDataURL('image/png')}' style='height: ${cheight}px;width:${cwidth}px'/>`;
$('.canvas-img').append(canvasImg);
})
三、文字换行
function toFormateStr (str, draw_width, startX, startY) {
var strWidth = ctx.measureText(str).width; // 测量文本尺寸信息(宽度)
var keyStr = '', sreLN = strWidth / draw_width;
var liner = Math.ceil(sreLN); // 计算文本一共能生成多少行
let strlen = parseInt(str.length / sreLN); // 等比缩放测量一行文本显示多少个字符
if (strWidth < draw_width) {
ctx.fillText(str, startX, startY);
} else {
for (var i = 1; i < liner + 1; i++) {
let startPoint = strlen * (i-1);
keyStr = str.substr(startPoint, strlen);
ctx.fillText(keyStr, startX, startY);
startY = startY + 20;
}
}
}
toFormateStr('这是一段长文字',200,20,35);//文字描述,文字宽度,文字X坐标,Y坐标