biji/前端/前端通过页面(dom)生成图片并放大倍数.md

39 lines
1.5 KiB
Markdown
Raw Normal View History

2020-02-11 14:16:07 +08:00
### 代码
2020-02-11 14:15:07 +08:00
```
var canvas2 = document.createElement("canvas");
var _canvas = document.getElementById('app');
var w = parseInt(window.getComputedStyle(_canvas).width);
var h = parseInt(window.getComputedStyle(_canvas).height);
//将canvas画布放大若干倍然后盛放在较小的容器内就显得不模糊了
var times = 3;
canvas2.width = w * times * window.devicePixelRatio;
canvas2.height = h * times * window.devicePixelRatio;
canvas2.style.width = w + "px";
canvas2.style.height =h + "px";
var context = canvas2.getContext("2d");
context.scale(times, times);
console.log(canvas2.style.width)
new html2canvas(document.getElementById('app'), {
canvas:canvas2,
allowTaint: true,
taintTest: true,
useCORS: true,
background: null,
windowWidth:document.body.scrollWidth,
windowHeight:document.body.scrollHeight,
2020-02-11 14:16:07 +08:00
x:0,
2020-02-11 14:15:07 +08:00
y:0
}).then(canvas => {
2020-02-11 14:21:37 +08:00
//canvas就是绘制完成的画板对象
2020-02-11 14:15:07 +08:00
});
}
})
2020-02-11 14:16:07 +08:00
```
2020-02-11 14:22:07 +08:00
html2canvas与canvas参考文档
### 重点介绍
2020-02-11 14:22:37 +08:00
context.scale(x 倍数, y 倍数); //这个是画板放大指定倍数
2020-02-11 14:17:37 +08:00
canvas2.width = w * times * window.devicePixelRatio; //指定画板宽度
canvas2.height = h * times * window.devicePixelRatio; //指定画板宽度
2020-02-11 14:52:37 +08:00
为什么要再乘以window.devicePixelRatio这个其实是设备的dipcanvas设置的宽度是像素 但是页面的单位是px 1px = 1dip 这样就会让页面超出canvas 让截图出现放大 并且显示不完全。
2020-02-11 14:21:07 +08:00
这就是原因也是卡了两天的bug。