【html2canvas】使用方法以及相关问题解决

Vue使用html2canvas方法

1.安装

npm install --save html2canvas

2.在需要使用的页面中引用

import html2canvas from 'html2canvas';

3.调用使用

			this.$nextTick(() => {
				html2canvas(this.$refs.vueDomSaveToImage).then((res) => {
					let imgUrl = res.toDataURL('image/jpg');
					const save_link = document.createElementNS(
						'http://www.w3.org/1999/xhtml',
						'a'
					);
					save_link.href = imgUrl;
					save_link.download = this.fileName + '.jpg'; //保存文件名格式为 ***-点名册、会议纪要、等文件名
					const event = document.createEvent('MouseEvents');
					event.initMouseEvent(
						'click',
						true,
						false,
						window,
						0,
						0,
						0,
						0,
						0,
						false,
						false,
						false,
						false,
						0,
						null
					);

                    //将图片以blob方式下载
					async function downloadImage(imgUrl, name) {
						try {
							const response = await fetch(imgUrl);

							if (!response.ok) {
								throw new Error(`HTTP error! status: ${response.status}`);
							}

							const blob = await response.blob();
							const url = window.URL.createObjectURL(blob);
							const link = document.createElement('a');
							link.href = url;
							link.download = name + '.jpg';
							link.click();

							this.$notify({
								title: this.fileName,
								message: '[' + this.fileName + ']' + '保存成功!',
								position: 'bottom-right',
								type: 'success',
								duration: 0,
							});
						} catch (error) {
							console.error('Error downloading image:', error);
						}
					}

					downloadImage(save_link, this.fileName).then(() => {
						console.log('finfish');
						this.$notify({
							title: this.fileName,
							message: '[' + this.fileName + ']' + '保存成功!',
							position: 'bottom-right',
							type: 'success',
						});
					});
				});
			});

遇到的问题及解决方法

1.图片导出后变形/比例改变了

图片可能使用了不支持的css属性,比如:object-fit:cover

解决方法:

更换其他css属性以达到需求,比如使用flex以使图片比例不改变居中

.fu{
	width: 1240px;
	height: 720px;
	overflow: hidden;
	display: flex;
	justify-content: center;
	align-items: center;
}
.img {
	width: 100%;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值