需要做一個生成海報的功能,然后發現生成的圖片會特別模糊;現在來記錄一下解決方案:
這里使用的是背景圖,然后生成圖片,生成以后的圖片:效果非常模糊 圖片大小226kb

依據:
| 名稱 | 默認值 | |
| dpi | 96 | 將分辨率提高到特定的DPI(每英寸點數) |
| scale | 1 | 按比例增加分辨率 (2=雙倍) |
所以只要增大dpi或者scale肯定能使同樣寬高的圖像變得清晰。
方法1:利用增大dpi
dpi:DPI是指某些設備分辨率的度量單位。DPI越低,掃描的清晰度越低,DPI越高,清晰度越高。
由於受網絡傳輸速度的影響,web上使用的圖片都是72dpi,照片使用300dpi或者更高350dpi,會很清晰。
html2canvas(template, {
dpi: 300,//加了一個這個設置
onrendered: function (canvas) {
var imgURL = canvas.toDataURL('image/png');
$('#downloadImg').attr('src',imgURL);
$('.poster-module').addClass('on');
},
useCORS: true, //(圖片跨域相關)
allowTaint: false, //允許跨域(圖片跨域相關)
x: 0,//頁面在橫向方向上的滾動距離 橫向上沒有超過 所以設置為0
y: window.pageYOffset,//頁面在垂直方向上的滾動距離 設置了以后 超過一屏幕的內容也可以截取
windowWidth: document.body.scrollWidth,//獲取在x軸上滾動條中內容
windowHeight: document.body.scrollHeight,//獲取在y軸上滾動條中內容
});
清晰很多,效果:

方法2:增大scale
//獲取設備比
function getDPR(){
if (window.devicePixelRatio && window.devicePixelRatio > 1) {
return window.devicePixelRatio;
}
return 1;
}
var template = document.getElementById('module');
// 放大canvas
function scaleCanvas(){
// 要轉換的模板dom
var dom = template;
// window.getComputedStyle 獲取元素的樣式
const box = window.getComputedStyle(dom); //這個方法 介紹 https://www.runoob.com/w3cnote/window-getcomputedstyle-method.html
// 獲取DOM 節點計算后寬高 取到的內容是385.993px
const width = box.width.replace('px','')
const height = box.height.replace('px','')
// 獲取像素比
const scaleBy = getDPR();
// 創建自定義 canvas 元素
const canvas = document.createElement('canvas');
// 設定 canvas 元素屬性寬高為 DOM 節點寬高 * 像素比
canvas.width = width * scaleBy;
canvas.height = height * scaleBy;
// 設定 canvas css寬高為 DOM 節點寬高
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
// 獲取畫筆
const context = canvas.getContext('2d');
// 將所有繪制內容放大像素比倍
context.scale(scaleBy, scaleBy);
var rect = template.getBoundingClientRect(); //獲取元素相對於視察的偏移量
context.translate(-rect.left, -rect.top); //設置context位置,值為相對於視窗的偏移量負值,讓圖片復位
html2canvas(template, {
canvas,//將放大的cnavas作為參數傳進去
// dpi: 300,
onrendered: function (imgCanvas) {
var imgURL = imgCanvas.toDataURL('image/png');
$('#downloadImg').attr('src',imgURL);
$('.poster-module').addClass('on');
},
useCORS: true, //(圖片跨域相關)
allowTaint: false, //允許跨域(圖片跨域相關)
});
}
這里有一個注意點,就是放大以后,繪制,會有一個偏移,所以要調整這個偏移量
效果:清晰了,圖片大小 336kb

方法3
將背景圖用img引入,通過定位,設置z-index來,css代碼就不附上了
效果:比之前直接背景圖,清晰了一些,但是還是有點模糊 ,圖片大小 256kb

方法4
之前使用的版本是
0.5.0-beta3
現在 換了一個版本
1.0.0-rc.5
使用圖片不用背景圖,生成得海報
html2canvas(template,{
allowTaint: false,
useCORS: true,
height: template.offsetHeight,
width: template.offsetWidth,
windowWidth: document.body.scrollWidth,
windowHeight: document.body.scrollHeight,
}).then(function (imgCanvas) {
var imgURL = imgCanvas.toDataURL('image/png');
$('#downloadImg').attr('src',imgURL);
$('.poster-module').addClass('on');
});
效果 變清晰了 ,看來還是使用最新版本得 bug更少一點

