[Vue] Convert a div on the page into a base64 image and download it locally. Vue, h5 pages download pictures to the local. Page conversion base64 file download to local


foreword

Continuing from the previous article, generate a QR code with log.
Save the QR code locally


提示:以下是本篇文章正文内容,下面案例可供参考

Steps for usage

1. Introduce the html2canvas library

The code is as follows (example):

npm install --save html2canvas

2. Introduced in the page

The code is as follows (example):

import html2canvas from "html2canvas"

3. Introduced in the page

// 保存二维码图片
saveImageCode() {
    
    
	html2canvas(this.$refs.downImg).then(canvas => {
    
    
		// 转成图片,生成图片地址
		let imgUrl = canvas.toDataURL("image/png"); //可将 canvas 转为 base64 格式
		console.log(imgUrl);
		let a = document.createElement('a')
		a.href = imgUrl;
		a.download = "文件分享二维码"; //文件名
		document.body.appendChild(a);
		a.click(); // 触发点击
		document.body.removeChild(a); // 然后移除
					
		// Dialog.alert({
    
    
		// 	message: '请长按图片保存到本地',
		// 	confirmButtonColor:"#418AF1"
		// }).then(() => {
    
    
		// 	// on close
		// 	ImagePreview([imgUrl]);
		// });
	});
},

Notice

On the PC side, you can use the a tag to download the base64 file, but on the mobile side, it is on the mobile phone. It is not possible to download base64 files.

Here I use VantUI's picture preview component. Then add a prompt statement to let the user press and hold to save.
Vant image preview official address

Unless the base64 file is passed to the background, the background will give an address. Otherwise there is no better way. I searched all over csdn. There are no tutorials that do it.


If it is a mobile terminal, comment the click event and uncomment the image preview
ImagePreview('image path']); this is the statement for vantui to preview the image

It needs to be introduced when using it.

Guess you like

Origin blog.csdn.net/qq_51055690/article/details/127979392