- 小程序
- 用小程序的 getSystemInfoSync() api获取设备像素,导出的宽高乘以物理像素
const sys = swan.getSystemInfoSync();
swan.canvasToTempFilePath({
x: canvasConf.x || 0,
y: canvasConf.y || 0,
width: canvasConf.w || 331,
height: canvasConf.y || 500,
destWidth: (canvasConf.dw || 331) * (sys.pixelRatio || 1),
destHeight: (canvasConf.dh || 500) * (sys.pixelRatio || 1),
canvasId: canvasConf.canvasId || 'canvas',
fileType: canvasConf.fileType || 'png',
quality: canvasConf.quality || 1,
success: res => {
saveImgToPhotos(res.tempFilePath);
},
fail: err => {
swan.showToast({
title: '保存失败',
icon: 'none'
});
}
});
- h5
将canvas的宽高及画的图片宽高扩大设备的物理像素,最终渲染的图片用img图片指定渲染的宽高(即canvas比要渲染的图片尺寸大)
let c = document.getElementById('canvas');
let cxt = c.getContext('2d');
// 像素有点虚,canvas扩大1倍画
getPixelRation(context) {
let backingStore = context.backingStorePixelRatio
|| context.webkitBackingStorePixelRatio
|| context.mozBackingStorePixelRatio
|| context.msBackingStorePixelRatio
|| context.oBackingStorePixelRatio
|| context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
}
let ratio = getPixelRation(cxt);
c.width = 331 * ratio;
c.height = 333 * ratio;
// 背景图片路径
let bgImg = new Image();
bgImg.crossOrigin = 'Anonymous';
bgImg.src = bgImg;
// 二维码
let qrcode = new Image();
qrcode.crossOrigin = 'Anonymous';
qrcode.src = qrcodeUrl;
// logo
let logo = new Image();
logo.crossOrigin = 'Anonymous';
logo.src = LOGO;
setTimeout(() => {
cxt.drawImage(bgImg, 0, 0, c.width, c.height);
cxt.drawImage(qrcode, 97.5 * ratio, 124 * ratio, 136 * ratio, 136 * ratio);
cxt.drawImage(logo, (97.5 + 104 / 2) * ratio, (124 + 104 / 2) * ratio, 32 * ratio, 32 * ratio);
this.imgUrl = c.toDataURL('image/png');
}, 550);