将html生成图片

将html生成图片

需求

  • 将html页面导出为一张图片

工具

  • html2canvas

安装

npm install --save html2canvas

导入

import html2canvas from 'html2canvas'

使用

  1. 绘制html区域
<div id="informBrand">测试</div>
<a-button type="primary" icon="download" @click="download">导出</a-button>
  1. 下载方法
    download(){
		  const canvas2 = document.createElement('canvas');
		  let _canvas = document.getElementById('informBrand');
		  const w = parseInt(window.getComputedStyle(_canvas).width);
		  const h = parseInt(window.getComputedStyle(_canvas).height);
		  //将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
		  canvas2.width = w * 2;
		  canvas2.height = h * 2;
		  const context = canvas2.getContext('2d');
		  context.scale(1, 1);
		  window.scrollTo(0, 0); //这一步是必须的 不然下载的图片会出现偏移
		  html2canvas(_canvas, { canvas: canvas2 }).then(function(canvas) {
			const imgUrl = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream'); // 获取生成的图片的url
			console.log(imgUrl)
			window.location.href = imgUrl; // 下载图片
      });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值