html2canvas生成图片模糊
2019-12-16 本文已影响0人
雅雅的前端工作学习
其实网上教程很多,但是往往因为没有注明所用html2canvas.js的版本,而导致代码报错
原理:放大canvas的画布尺寸(尺寸为window.devicePixelRatio),这样 物理像素与设备独立像素(dips)就可以契合的填充,代码如下:
//截图目标div
const dom = $("#html2canvas")[0];
// 创建一个新的canvas
const Canvas = document.createElement('canvas');
const width = document.body.offsetWidth; // 可见屏幕的宽
const height = document.body.offsetHeight; // 可见屏幕的高
const scale = window.devicePixelRatio; // 设备的devicePixelRatio
// 将Canvas画布放大scale倍,然后放在小的屏幕里,解决模糊问题
Canvas.width = width * scale;
Canvas.height = height * scale;
Canvas.getContext('2d').scale(scale, scale);
html2canvas(dom, {
canvas: Canvas,
scale,
useCORS: true,
logging: true,
width: width + 'px',
hegiht: height + 'px',
}).then((canvas) => {
const context = canvas.getContext('2d');
// 关闭抗锯齿形
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
// canvas转化为图片,这里使用了Canvas2Image.js哦,不引入会报错的
const img = Canvas2Image.convertToImage(canvas, canvas.width, canvas.height);
console.log(img);
document.body.appendChild(img);
img.style.cssText = "width:100%;height:100%;position:absolute;top:0;left:0;right:0;bottom:0;opacity:0;";
alert("海报生成成功,请长按保存");
})