JavaScript将网页以图片的形式下载到电脑
接到老板需求,有个网页,上面有参赛二维码,不希望用户手动截图,所以问,能不能有个功能(按钮)之类的,点一下就可以把这整个网页直接下载到用户电脑。作为一名 “不怕死” (手动狗头)的前端程序员,当然要接下来这个活咯。
不扯了干正事。。。。。。。
查了查资料,发现html2canvas这个库和FileSaver搭配着用刚好满足需求,那么就上代码。
<html>
<body>
<a onclick="downloadImage()"></a>
</body>
</html>
<script>
const downloadImage = function () {
html2canvas(document.querySelector("body")).then(function (canvas) {
canvas.toBlob(function (blob) {
saveAs(blob, new Date().getTime() + ".png");
});
})
}
</script>
document.querySelector(“body”)意思就是要把那些内容转成图片,如果你只想转某一部分,那就写那部分最外层的容器id或者class就可以了。
写完之后发现这个功能其实已经可以用了,但是出了点小问题,网页中的图片部分转成图片后,莫名消失了,然后控制太报了CORS错误???
啥也别说了,走看看官网的配置项!官网链接地址
发现了一个配置useCORS:是否尝试使用 CORS 从服务器加载图像,那么把这个加上再试试。
<html>
<body>
<a onclick="downloadImage()"></a>
</body>
</html>
<script>
const downloadImage = function () {
html2canvas(document.querySelector("body"), {
useCORS: true
}).then(function (canvas) {
canvas.toBlob(function (blob) {
saveAs(blob, new Date().getTime() + ".png");
});
})
}
这次好多静态图片都没问题了,但是有一个二维码始终报跨域错误。好家伙。。。
不卖关子了,网上好多资料都找了,什么img加cors属性,允许跨域一堆,前端将图片url链接转base64也不行,因为转base64需要使用到XMLHttpRequest库,请求就又会跨域。无奈,谁让咱是全栈呢,前端搞不定就后端搞嘿嘿嘿。
注意:如果图片模糊尽量不要使用background: url(xxx), 使用 img src=“base64” 去替换会发现清楚特别多。
附上后端代码
public string base64 = string.Empty;
string url = string.Format("http://2019.xxxx.com/Qrcode.aspx?code=http://xxxx.chinashop.cc/Pre-registration/3/index.html?qd={0}", zsid);
using (WebClient webClient = new WebClient())
{
byte[] bytes = webClient.DownloadData(url);
base64 = string.Format("data:image/png;base64,{0}", Convert.ToBase64String(bytes));
}
ok将图片在服务器端转成base64格式,就ok了。
最后优化一下前端代码。
<html>
<body>
<a onclick="downloadImage()"></a>
</body>
</html>
<script>
// 也没有怎么优化,就是加个防抖。
function debounce(fn, immediate, delay) {
let timer = undefined;
return function () {
if (timer) {
clearTimeout(timer);
}
if (immediate) {
let bool = !timer;
timer = setTimeout(function () {
timer = undefined;
}, delay);
if (bool) {
return fn.apply(this, arguments);
}
return;
}
timer = setTimeout(function () {
fn.apply(this, arguments)
}, delay)
}
}
const downloadImage = debounce(function () {
// 加这两行主要是为了,保存图片的时候不希望把这个按钮也保存进去
var dom = document.querySelector(".btn_container");
// 先隐藏这个按钮
dom.style.display = "none";
html2canvas(document.querySelector("body"), {
useCORS: true
}).then(function (canvas) {
canvas.toBlob(function (blob) {
saveAs(blob, new Date().getTime() + ".png");
});
// 保存完之后再放开就行了
dom.style.display = "flex";
})
}, true, 1500)
感谢观看。